问题
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