如本 issue 中所建议,如果我想引用子组件,建议使用 refs。
findDOMNode(childComponentStringRef)
class Field extends Component {
componentDidMount() {
// this.inputNode.focus(); // Basically I want to access the ref to input here as well
}
render() {
return (
<input type='text' ref={this.props.inputRef} />
)
}
}
class MyComponent extends Component {
componentDidMount() {
this.inputNode.focus();
}
render() {
return (
<div>
Hello, <Field inputRef={node => this.inputNode = node} />
</div>
)
}
}
我想要的是访问 Field
组件内的 input
的 ref。那么我们该怎么做呢?
我试过用
this.props.inputRef
this.inputRef
但没有一个有效。请在这方面指导我。
最佳答案
您可以传递一个将 refs 作为 prop 存储在父组件中的函数。我做了一个fiddle给你举个例子。
class Field extends Component {
componentDidMount() {
this.props.setChildRef('inputRef', this.inputRef);
this.inputRef.focus(); // Basically I want to access the ref to input here as well
}
render() {
return (
<input type='text' ref={ip=> this.inputRef= ip} />
)
}
};
class MyComponent extends Component {
componentDidMount() {
this.inputRef.focus();
}
setChildRef = (name, ref) => {
this[name] = ref;
}
render() {
return (
<div>
Hello, <Field setChildRef={this.setChildRef} ref={node => this.inputNode = node} />
</div>
)
}
}
关于javascript - ReactJs:如何获取引用来自其父项的组件的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564565/