使用 Flow Typings 反应 useRef Hook

Tim*_*nen 8 web-component reactjs flowtype react-hooks

我正在使用带有 Flow 类型的 React useRef,并且我正在尝试为第三方 Web 组件库编写一个包装器组件。

Web 组件需要一个 changeCallback 函数,我正在使用 ref 将其分配给 ref。

function RadioButtonGroup({ onChange, children }) {
    const ref: { current: null | ElementRef<ElementType> = React.useRef(null);

    React.useEffect(() => {
        if (ref.current) ref.current.changeCallback = onChange;
    }, [onChange]);

    return <web-component ref={ref}>{children}</web-component>
}
Run Code Online (Sandbox Code Playgroud)

由于 HTMLElement 不包含名为 changeCallback 的属性,因此流程会引发错误。

无法分配给handleChangeref.current.changeCallback因为属性changeCallback缺失 HTMLElement

我尝试使用这样的属性扩展“ElementType”

ElementRef<ElementType & { changeCallback: Function }>
Run Code Online (Sandbox Code Playgroud)

但这会导致以下错误:

无法实例化,ElementRef因为对象类型 [1] 不是 React 组件。

Web 组件不会在更改时触发“更改”事件。它执行函数changeCallback。这是库的文档。

// MyComponent.js

class MyComponent extends Component {

    constructor() {
        // ...

        // Create a ref
        this.sdxSelectEl = React.createRef();
    }

    componentDidMount() {
        // Attach callback here to ref
        this.sdxSelectEl.selectCallback = (selection) => console.log(selection);
    }

    render() {
        // ...
        <sdx-select ref={el => (this.sdxSelectEl = el)} />
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*nen 5

解决方案是使用显式类型参数调用 useRef 来表示预期类型:

const ref = React.useRef<null | (HTMLElement & { changeCallback: Function })>(null);
Run Code Online (Sandbox Code Playgroud)