【问题标题】:How do I pass React.createRef() to a child component?如何将 React.createRef() 传递给子组件?
【发布时间】:2019-06-27 13:27:08
【问题描述】:

在我的侧边栏中,我有一个单选按钮列表,每个按钮应该选择位于我的应用程序主要区域中的一个组件。我想设置它,以便当我单击选择它的单选按钮时组件滚动到视图中,据我所知,我需要引用该组件才能将其滚动到视图中,但是我遇到了麻烦因为我不知道如何正确地将引用从子组件传递给父组件。

父组件是一个类组件,在它的构造函数中我这样设置createRef()

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

然后我创建了一个应该传递给子组件并返回 ref 的函数:

getElem(ref) {
  this.myRef = ref;
}

现在,在父组件的渲染中,我将函数传递给子组件,如下所示:

<Designer 
  usedComponents={this.state.usedComponents}
  myRef={this.getElem}
/>

Designer 组件中,我映射主要区域组件并将引用传递给它们,如下所示:

const components = props.usedComponents.map((component, index) => {
  return (
    <div onMouseUp={() => props.selectComponent(index)} key={index}>
      <DesignerComponent {...component} myRef={props.myRef} />
    </div>
  );
});
return components;

DesignerComponent 组件是通过 switch 语句确定的,因为每个组件都有一组不同的 props,但在 switch 语句中,我还将 myRef={props.myRef} 传递给每个单独的组件,然后我在每个单独的组件中设置 ref,如下所示:

<section ref={props.myRef}></section>

但是,这会破坏我的应用程序并给我这个错误消息:

“TypeError:无法设置未定义的属性'myRef'”。

我做错了什么?

【问题讨论】:

  • 你必须使用forward ref
  • 我也发现了这个,但我不知道如何实现它。
  • 尝试设置您的const components = [Array].map((item) =&gt; React.forwardRef(props, ref) =&gt; &lt;Component ref={ref} {...props}/&gt;)
  • 哪个组件是父组件?
  • 前 3 块代码的所有内容都在父组件内。

标签: reactjs


【解决方案1】:

我想通了。函数 getElem(ref) 似乎没有做任何事情。我只是将 myRef={this.myRef} 传递给 Designer 组件,现在它可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 2020-05-07
    • 2020-03-30
    • 2017-12-02
    相关资源
    最近更新 更多