What's the proper way of passing a ref to a prop?

前端 未结 3 1269
一个人的身影
一个人的身影 2020-12-24 05:55

I\'m trying to pass a ref of a component to another component. Since string refs are being deprecated I\'m using callback refs.

So I have something similar to this:<

3条回答
  •  轮回少年
    2020-12-24 06:33

    In general the "ref" feature is an anti-pattern in React. It exists to enable side-effect driven development, however in order to benefit the most from the React way of programming you should try to avoid "refs" if possible.

    As for your particular issue, passing a child a ref to it's sibling is a chicken vs. egg scenario. The ref callback is fired when the child is mounted, not during render which is why your example doesn't work. One thing you can try is pushing the ref into state and then reading from state into the other child. So:

     !this.state.one && this.setState({ one: c })}/>
    
    

    Note: without the !this.state.one this will cause an infinite loop.

    Here is a codepen example of this working (look at the console to see the sibling ref logged): http://codepen.io/anon/pen/pbqvRA

提交回复
热议问题