javascript - 如何在 HOC 中将 ref 添加到按钮
问题描述
https://codesandbox.io/s/agitated-field-uctfd?file=/src/App.js
我有一个返回按钮的组件:
const Button = props => <button ref={?} style={{ color: props.color }}>bt</button>;
我正在尝试了解 HOC 和 refForwarding。这是一个 HOC 组件:
const colorer = Button => {
const ButtontWithRef = React.forwardRef((props, ref) => {
return <Button {...props} ref={ref} />;
});
class Colored extends React.Component {
render() {
return <ButtonWithRef color="red" ref={this.props.passedRef} />;
}
}
return Colored;
};
组件中使用的彩色按钮:
const Colored = colorer(Button);
我正在button
尝试Button
使用ref
. ref
但是当Button
通过 HOC( colorer
)时,我不知道如何转发。当我 console.logref
我得到
Object {current: null}
应用程序.js:
export default function App() {
const myRef = React.createRef();
console.log(myRef);
return (<Colored passedRef={myRef} />);
}
如何将其设置ref
为实际的button
内部Button
?
解决方案
按钮组件可以利用forwardRef
并传递ref
给实际的按钮组件
const Button = React.forwardRef(
(props, ref) => <button ref={ref} style={{ color: props.color }}>bt</button>
);
其余代码将保持不变,除了您将使用的 App 组件内部useRef
,React.createRef
因为 App 是一个功能组件
const colorer = Button => {
const ButtontWithRef = React.forwardRef((props, ref) => {
return <Button {...props} ref={ref} />;
});
class Colored extends React.Component {
render() {
return <ButtonWithRef color="red" ref={this.props.passedRef} />;
}
}
return Colored;
};
...
export default function App() {
const myRef = useRef(null);
console.log(myRef);
return (<Colored passedRef={myRef} />);
}
推荐阅读
- angular - 防止 PrimeNg 中的 NodeExpand 事件
- c++ - 如何传递大小未知的 std::array?在 C++ 中
- apache-kafka - 使用 Kafka Streams 在输出中设置时间戳
- gitlab - 将外部文件添加到本地存储库后 git push 出错
- angular - 使用角度4以数组格式获取多个复选框值
- c# - 在 Windows 启动时自动以管理员身份运行
- firebase - 检索 Firestore 对象颤动
- gaussian - 来自 mfcc 特征的高斯混合模型
- mongodb - 与时间序列聚合中先前记录的时间差
- python-3.x - 使用 LSTM 在在线多类分类中的每次迭代中给出相同值的预测