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

前端 未结 3 1278
一个人的身影
一个人的身影 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条回答
  •  猫巷女王i
    2020-12-24 06:21

    This is now much simpler using the new ref api (available since React 16 - thanks to perilandmishap for pointing that out).

    class MyComponent extends React.Component {
      constructor (props) {
        super(props);
        this.oneRef = React.createRef();
      }
    
      render () {
        return (
          
            
            
          
        }
      }
    }
    

    You would consume the prop in Two like:

    this.props.one.current
    

    A few things of note with this approach:

    The ref will be an object with a current property. That property will be null until the element/component is mounted. Once it's mounted, it will be the instance of One. It should be safe to reference it once is mounted.

    Once the instance is unmounted, the current property on the ref returns to being null.

提交回复
热议问题