React - Passing ref from dumb component(child) to smart component(parent)

*爱你&永不变心* 提交于 2020-02-01 01:51:06

问题


I have one smart and one dumb component, I need to have ref to an element which is in my the dump component in my smart component: can I pass it with props or??

Dumb:
export default (props)=>{
return(
    <input type='number' ref='element'}/>
);}

Smart:
class Parent extends Component {
    constructor(props) {
        super(props);
    }
componentDidMount() {
    const node = this.refs.element; // undefined
    }
render(){
    return <Dumb { ...this.props }/>
    }
}

回答1:


You could use the callback syntax for refs:

// Dumb:
export default props =>
    <input type='number' ref={props.setRef} />

// Smart:
class Parent extends Component {
    constructor(props) {
        super(props);
    }

    setRef(ref) {
        this.inputRef = ref;
    }

    render(){
        return <Dumb {...this.props} setRef={this.setRef} />
    }
}



回答2:


With react^16.0.0 you would use React.createRef(). Using @Timo's answer, it would look like this:

// Dumb:
export default props =>
    <input type='number' ref={props.setRef} />

// Smart:
class Parent extends Component {
    constructor(props) {
        super(props);
        this.ref1 = React.createRef()
    }

    render(){
        return <Dumb {...this.props} setRef={this.ref1} />
    }
}



回答3:


As per DOC:

You may not use the ref attribute on functional components because they don't have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state.

So i think, if you want to use the ref, you need to use class.

Check this: https://github.com/facebook/react/issues/4936




回答4:


If you need dynamic refs, because you have an array or something, like I did. Here is what I came up with after reading the answers above.

Also this assumes the myList is an array of objects with a key property. Anyways you get it.

Also this solution works without any issues from TypeScript as well.

const Child = props => <input ref={refElem => setRef(props.someKey, refElem)} />

class Parent extends Component {

    setRef = (key, ref) => {
      this[key] = ref; // Once this function fires, I know about my child :)
    };

    render(){
        return (
          {myList.map(listItem => <Child someKey={listItem.key} setRef={this.setRef} />)}
        )
    }
}

Anyways hope this helps someone.



来源:https://stackoverflow.com/questions/42980402/react-passing-ref-from-dumb-componentchild-to-smart-componentparent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!