首页 > 解决方案 > 如何在 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);
    }
    }
    })

}
}
}

非常感谢!

标签: reactjscomponentsrefs

解决方案


是的,您可以通过以下方式将 ref 传递给子组件:

<CusComponent ref={this.a}>

确保您创建CusComponentwithReact.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>;
  }
}

推荐阅读