简体   繁体   English

React - 如何给每个子组件一个唯一的引用?

[英]React - How do I give each child component a unique ref?

I have a parent component that renders one of several child components:我有一个父组件,它呈现几个子组件之一:

class Parent extends React.Component {
  ...
  render() {
    const activeChild = this.state.activeChild; // 0, 1, 2, etc.
    return (
      <div>
        {this.props.children[activeChild]}
      </div>
    );
  }
}

Each of these child components needs to have a ref to its own unique DOM node.这些子组件中的每一个都需要有一个对它自己唯一的 DOM 节点的ref In my case, I need to pass each child's node to a third-party library to draw something on it (for example: a visualization, a canvas, or a map).就我而言,我需要将每个子节点的节点传递给第三方库以在其上绘制某些内容(例如:可视化、画布或地图)。

The problem is that, when the child components are rendered to the same 'point' in the React tree, at different times, they all end up sharing the same ref .问题是,当子组件在 React 树中呈现到相同的“点”时,在不同的时间,它们最终都会共享相同的ref (I think) (我认为)

Here's a JSFiddle demonstrating the problem, using Leaflet.js.这是一个使用 Leaflet.js 演示该问题的 JSFiddle。

When all of the children are rendered separately, they each get their own DOM node to draw their map onto.当所有的孩子被单独渲染时,他们每个人都有自己的 DOM 节点来绘制他们的地图。 But when they are shown one-at-a-time, only the first one is able to draw onto the ref 'd DOM node.但是当它们一次显示一个时,只有第一个能够绘制到ref 'd DOM 节点上。

Can I tell React to use (and display) separate nodes for each individual child's ref , even if the children are being mounted at the same point?我可以告诉 React 为每个单独的孩子的ref使用(和显示)单独的节点,即使孩子被安装在同一点?

If not, is there a better approach to this problem?如果没有,有没有更好的方法来解决这个问题?

If you mean ref the ref and not the key , try something like this:如果您的意思是 ref ref而不是key ,请尝试以下操作:

class Parent extends React.Component {
  ...
   constructor(props) {
        super(props);
        this.myRef = React.createRef();
   }
  render() {
    const activeChild = this.state.activeChild; // 0, 1, 2, etc.
    const ChildComponent = this.props.children[activeChild];

    return (
      <div>
        <ChildComponent ref={this.myRef} />
      </div>
    );
  }
}

I did not test this.我没有测试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM