我在react-native中有一个搜索栏组件,它是在父组件中导入的,
SearchBar子组件具有以下元素:
<Search
ref={component => this._search = component}
onChangeText={this.searchUpdated}
blurOnSubmit
useClearButton={false}
backgroundColor='#15A5E3'
/>
searchUpdated(term) {
return new Promise((resolve, reject) => {
this.setState({ searchTerm: term });
resolve();
});
}是否可以在导入该子组件的父项中访问该子组件的状态?提前感谢你的帮助
发布于 2018-06-12 00:25:16
你可以设置任何react组件的'ref‘属性,然后在父组件中,你可以像这样访问子组件中的任何方法:
this.refs.child.childMethod()举个例子:
子组件
class ChildComponent extends Component {
getState() {
return this.state
}
render() {
return <Text>I'm a child</Text>
}
}父组件:
class ParentComponent extends Component {
manipulateChildState() {
let child = this.refs.childRef.getState()
// do something here
}
render() {
return <Child ref='childRef' />
}
}只需记住在this.refs.REFERENCE和prop ref='REFERENCE‘上使用相同的字符串。
https://stackoverflow.com/questions/50800432
复制相似问题