reactjs - 如何在 React 中将 refs 传递给组件
问题描述
我有这样的数据:
constructor(props) {
this.a = React.createRef();
this.b = React.createRef();
this.c = React.createRef();
}
setValue = (data = {}) => {
const {a='', b='', c=''} = data.constructor === ({}).constructor ? data : {};
this.a.current.setValue(a, data => {
this.b.current.setValue(data.b, data => {
this.c.current.setValue(data.c);
}
}
}
}
我怎么能像这样将它传递给我的自定义组件:
<CusComponent ref={this.a}>
这是在 CusComponent 中获取值的函数:
value = function (a,b,c) {
if (arguments.length) {
if (a) {
this.setState({a}, () => {
this.value_a.value(a);
if (b) {
this.setState({b}, () => {
this.value_b.value(b);
if (c) {
this.setState({c}, () => {
this.value_c.value(c);
}
}
})
}
}
}
非常感谢!
解决方案
是的,您可以通过以下方式将 ref 传递给子组件:
<CusComponent ref={this.a}>
确保您创建CusComponent
withReact.forwardRef
因为这会在ref
旁边创建一个参数props
。这个 `ref 你可以直接绑定到你的子组件中的任何东西。
const CusComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
));
您可以在文档中阅读有关此内容的更多详细信息。
但是,如果您的父组件和子组件都是类组件,则将 ref 传递给 CusComponent,如下所示:
<CusComponent childref={this.a}>
将属性命名为ref
. 然后您可以在子组件中访问此引用,如下所示。
export default class CusComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div ref={this.props.childref}>Here</div>;
}
}
推荐阅读
- python - 在 Django UpdateView 中覆盖 get() 方法会给出“str”没有属性获取错误
- angular - 反应形式的总和数组
- vba - 如何搜索字符串并突出显示相邻的单词?
- java - Netbeans Maven 项目中 ResourceBundle 的 Bundle 类路径无效
- arrays - 列表中总和的练习
- javascript - 动态插入到 DOM 后,样式不会应用于 HTML 元素 - Angular
- android - 我想要使用 android-studio 在 android 中以某个数字开头的按钮的代码
- pandas - 使用多个键转换熊猫数据框
- animation - 如何在 adobe animate 2021 中扭曲视频?
- c - C 调用具有空声明 arglist 的函数,使用 args 定义