React - 如何将`ref`从子组件传递到父组件? [英] React - How to pass `ref` from child to parent component?
本文介绍了React - 如何将`ref`从子组件传递到父组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个父组件和一个子组件,我想访问父组件中子组件中元素的 ref
.可以用 props 传递吗?
I have a parent and a child component, I want to access the ref
of an element which is in the child component, in my parent component. Can I pass it with props?
// Child Component (Dumb):
export default props =>
<input type='number' ref='element' />
// Parent Component (Smart):
class Parent extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const node = this.refs.element; // undefined
}
render() {
return <Dumb { ...this.props }/>
}
}
推荐答案
您可以使用 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} />
}
}
这篇关于React - 如何将`ref`从子组件传递到父组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文