我有这样的反应型观点。
<Parent>
<Header/>
</Parent>
标题也是具有一些文本输入字段和图标的视图。父级是通过添加页眉组件创建的另一个视图。因此,我想做的是,当我在“标题”视图中的文本字段上键入一些文本时,我想将该值用作“父视图”道具。这该怎么做???我尝试了一些StackOverflow中显示的答案。但是他们没有给我我所期望的。
对于想要查看完整代码的人,这是父屏幕。
export default class ParentScreen extends Component {
constructor(props) {
super(props);
this.state = {
objects: null,
indicator: true,
};
}
render(){
<View style={styles.container}>
<HeaderBar />
</View>
}}
这是“标题”屏幕。
export default class HeaderBar extends Component {
constructor(props) {
super(props);
}
state = {
searchEnabled: false
};
render() {
return (
<View style={styles.navigationBar}>
<View style={styles.titleArea}>
{this.state.searchEnabled === true ? (
<View style={styles.titleArea}>
<Icon
name="arrow-back"
type="Ionicons"
color="black"
onPress={() => this.setState({ searchEnabled: false })}
/>
<TextInput
placeholder="Search"
placeholderTextColor="white"
style={styles.input}
onChangeText={text => this.setState({ filterKey: text })}
/>
</View>
) : (
<View style={styles.titleArea}>
<Image
style={styles.profileImage}
source={require("../../images/user_image_1.jpg")}
/>
</View>
)}
</View>
</View>
);
}
}
答案 0 :(得分:2)
在父视图中定义一个函数,例如:
onChangeText = (text) => {
this.setState({
myUpdatedText: text
})
}
然后,将其作为道具传递给孩子:
<HeaderBar onChangeText={this.onChangeText} />
因此在子代码中,您可以像这样使用它:
<TextInput
placeholder="Search"
placeholderTextColor="white"
style={styles.input}
onChangeText={this.props.onChangeText}
/>