react-native - 如何在反应原生中从子视图中获取道具
问题描述
我有这样的反应原生观点。
<Parent>
<Header/>
</Parent>
标题也是一个带有一些文本输入字段和图标的视图。Parent 是通过添加 Header 组件创建的另一个视图。所以我想要做的是,当我在位于标题视图中的文本字段上键入一些文本时,我想将该值带到父视图道具。这该怎么做???我尝试了一些在 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>
);
}
}
解决方案
在父视图中定义一个函数,例如:
onChangeText = (text) => {
this.setState({
myUpdatedText: text
})
}
然后,将其作为道具传递给孩子:
<HeaderBar onChangeText={this.onChangeText} />
所以在子代码中你可以像这样使用它:
<TextInput
placeholder="Search"
placeholderTextColor="white"
style={styles.input}
onChangeText={this.props.onChangeText}
/>
推荐阅读
- reactjs - 当 App 嵌入 Drupal 时,在开发模式下运行 React App
- .net-core - 具有@ref 属性的 Blazor 中未显示模型弹出窗口
- google-sheets - 单元格中数字范围的自定义数字格式
- arrays - 在未排序的数组中搜索总和为一个值的 3 个元素
- mysql - 如何在 MySQL 表中设置正确的索引?
- c# - 按类型或字符串获取集合
- jenkins - 从文件夹共享库调用时,Jenkins groovy 代码失败
- angular - 自定义组件动画在拖放时在 Angular 9 + CDK 中不起作用
- oracle - 使用 impdp 将数百万行加载到安装了触发器的并行模式下的表中 (Oracle)
- sql-server - SSRS 中的钻取