我正在尝试使用React.forwardRef,但是如何让它在基于类的组件(而不是HOC)中工作.
docs示例使用元素和功能组件,甚至在高阶组件的函数中包装类.
所以,从他们的ref.js文件中的这样的东西开始:
const TextInput = React.forwardRef(
(props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />)
);
Run Code Online (Sandbox Code Playgroud)
而是将其定义为:
class TextInput extends React.Component {
render() {
let { props, ref } = React.forwardRef((props, ref) => ({ props, ref }));
return <input type="text" placeholder="Hello World" ref={ref} />;
}
}
Run Code Online (Sandbox Code Playgroud)
要么
class TextInput extends React.Component {
render() {
return (
React.forwardRef((props, ref) => (<input type="text" placeholder="Hello World" ref={ref} />))
);
}
}
Run Code Online (Sandbox Code Playgroud)
只有工作:/
另外,我知道我知道,参考不是反应方式.我正在尝试使用第三方画布库,并希望在单独的组件中添加一些工具,因此我需要事件监听器,因此我需要生命周期方法.以后它可能会走另一条路,但我想尝试一下.
文档说这是可能的!
Ref转发不仅限于DOM组件.您也可以将refs转发给类组件实例.
但后来他们继续使用HOC而不仅仅是课程.