![](/img/trans.png)
[英]React Native function scope (Call parent function from child function)
[英]React Native - Call Parent ref function from Child
我有一個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
prop作為函數傳遞:
<Child onClick={() => {
console.log('onclick of parent called!');
this.parentInput.clear();
// Add something more here
}}>
但是,對於高級用例,我建議使用任何狀態管理庫,例如Redux 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.