我有一个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
组件: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;
我知道我可以使用
Parent
清除this.parentInput.clear()
中父母的输入,但是如何从Child
组件中清除呢?提前致谢!
最佳答案
对于这种最简单的用例,您可以通过使用回调函数并将其作为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
,当您使用child时,将onClick
属性作为函数传递:<Child onClick={() => {
console.log('onclick of parent called!');
this.parentInput.clear();
// Add something more here
}}>
但是,对于高级用例,我建议使用任何状态管理库,例如Redux。