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

前端 未结 3 1285
一个人的身影
一个人的身影 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:14

    In general, if you need to pass a reference to something that may not be set at call time, you can pass a lambda instead:

     this.one = c}/>
     this.one}/>
    

    and then reference it as

    this.props.one()
    

    If it has been set when you call it, you'll get a value. Before that, you'll get undefined (assuming it hasn't otherwise been initialized).

    It bears noting that you won't necessarily re-render when it becomes available, and I would expect it to be undefined on the first render. This is something that using state to hold your reference does handle, but you won't get more than one re-render.

    Given all that, I would recommend moving whatever code was using the ref to One in Two up into the component that is rendering One and Two, to avoid all the issues with both this strategy, and the one in @Carl Sverre's answer.

提交回复
热议问题