【问题标题】:How to passing refs to component in React如何在 React 中将 refs 传递给组件
【发布时间】:2021-12-02 10:38:37
【问题描述】:

我有这样的数据:

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);
    }
    }
    })

}
}
}

非常感谢!

【问题讨论】:

    标签: reactjs components refs


    【解决方案1】:

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

    <CusComponent ref={this.a}>
    

    确保使用React.forwardRef 创建CusComponent,因为这会在props 旁边创建一个参数ref。这个 `ref 你可以直接绑定到你的子组件中的任何东西。

    const CusComponent = React.forwardRef((props, ref) => (
      <button ref={ref}>
        {props.children}
      </button>
    ));
    

    您可以在documentation 中阅读更多详细信息。

    但是,如果您的父组件和子组件都是类组件,则将 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>;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多