在组件类之间动态传递和更新 UI 和数据(React Native)



我的目标:在我的应用程序中,我有一个包装在TxtMsgTypePicker类中的选取器组件。我还有一个名为TxtMsgParamView的类,它需要从 TxtMsgTypePicker 类接收所选值,并且一旦 TxtMsgTypePicker 类选择了值,更新我的 TxtMsgParamView 类中的 UI 和数据。

这是我的代码:

export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
pickedTxtMsgType: enums.TxtMsgType.CONFIRM_PHONE_NUMBER
}
}
render() {
return (
<View style={styles.parentView}>
<View style={styles.view3}>
<TxtMsgParamView
onChangeText = {(text) => this.setState({text: text})}
txtMsgType = {this.state.pickedTxtMsgType}
>   
</TxtMsgParamView>
</View>
<View style={styles.view4}>
<TxtMsgTypePicker
onValueChange = {(pickedTxtMsgType) => this.onPickedTxtMsgType(pickedTxtMsgType)}
>
</TxtMsgTypePicker>
</View>
</View>
);
}
}

目前,我能够通过 props 将所选值从 TxtMsgTypePicker 类发送到 TxtMsgParamView 类。但是,问题不在于从 TxtMsgTypePicker 类获取值,问题是,当 TxtMsgTypePicker 类接收所选值时,TxtMsgParamView 类如何侦听 ,以便一旦选择了该值,TxtMsgParamView类就可以使用它执行操作,例如更新其数据和 UI?

再次感谢您的帮助!

主要问题是the problem is, how does TxtMsgParamView class listen for the when it recieves the selected value from the TxtMsgTypePicker,所以答案是:当你把道具放给你的孩子时,React组件会分别在道具上更新。如果它的道具没有改变,那么子组件将不会更新。

您必须阅读 React 如何更新组件的官方文档,我想您想在TxtMsgParamView中进行条件渲染,所以,请阅读这篇文章。

最新更新