Parent 组成部分:
Parent
import React, { Component } from "react"; import { View, TextInput } from "react-native"; class Parent extends Component { constructor(props) { super(props); this.state = { txt: "" }; } render() { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <TextInput ref={parentInput => { this.parentInput = parentInput; }} style={{ width: 200, height: 100 }} onChangeText={txt => this.setState({ txt })} value={this.state.txt} /> </View> ); } } export default Parent;
Child 组成部分:
Child
import React, { Component } from "react"; import { View, Text, TouchableOpacity } from "react-native"; class Child extends Component { constructor(props) { super(props); } render() { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <TouchableOpacity style={{ justifyContent: "center", alignItems: "center", width: 200, height: 100 }} onPress={() => { // ??? }} > <Text>Clear Input!</Text> </TouchableOpacity> </View> ); } } export default Child;
我知道我可以在中清除家长的输入 父母亲 使用 this.parentInput.clear() 但我怎样才能从法律上澄清这一点呢 小孩 组件?
父母亲
this.parentInput.clear()
小孩
提前谢谢!
prop .
prop
例如 Child
<TouchableOpacity style={{ justifyContent: "center", alignItems: "center", width: 200, height: 100 }} onPress={() => { this.props.onClick(); // <-- you might want to pass some args as well }} >
来自 Parent onClick 道具作为功能:
onClick
<Child onClick={() => { console.log('onclick of parent called!'); this.parentInput.clear(); // Add something more here }}>
然而,对于高级用例,我建议使用任何状态管理库,如 Redux .