У меня есть компонент 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?
Thanks in advance!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


В наиболее простом варианте использования, подобном этому, вы можете обойтись, используя функцию обратного вызова и передав ее как 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.info('onclick of parent called!');
this.parentInput.clear();
// Add something more here
}}>
Однако для расширенного использования я рекомендую использовать любые библиотеки управления состоянием, такие как Redux.