Reputation: 2702
I have a Parent
component:
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;
And I have a Child
component:
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;
I know I can clear the parent's input in the Parent
using this.parentInput.clear()
but how can I clear that from the Child
component?
Thanks in advance!
Upvotes: 0
Views: 647
Reputation: 3543
For the most simple use-case like this, you can get around by using a callback function and passing it as a prop
.
For example,
Child
:
<TouchableOpacity
style={{
justifyContent: "center",
alignItems: "center",
width: 200,
height: 100
}}
onPress={() => {
this.props.onClick(); // <-- you might want to pass some args as well
}}
>
And from Parent
, when you use child, pass the onClick
prop as function:
<Child onClick={() => {
console.log('onclick of parent called!');
this.parentInput.clear();
// Add something more here
}}>
However, for advanced use case, I recommend using any state management libraries like Redux.
Upvotes: 2