当父状态更改时,React Native NavigatorIOS 子组件不会更新
React Native NavigatorIOS Child Component Doesn't Update When Parent State Changes
当我按下 NavigatorIOS React Native 组件上的通知按钮时,我试图打开一个侧边菜单,但当父组件的状态发生变化时,子组件似乎没有更新。因此,按下通知按钮并没有按照我的意愿进行。父子组件如下。当使用 NavigatorIOS 更改父状态时,如何让子组件更新?
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
rightMenuOpen: false
}
this.rightButtonPress = this.rightButtonPress.bind(this);
}
rightButtonPress() {
this.setState({rightMenuOpen: true});
}
render() {
return (
<NavigatorIOS
initialRoute={{
component: Home,
rightButtonIcon: source=require('./img/notifications.png'),
onRightButtonPress: this.rightButtonPress,
passProps: {index: 1, rightMenuOpen: this.state.rightMenuOpen},
}}
style={{flex: 1}}
/>
)
}
}
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
const menu = <Switch/>
return (
<View style={styles.body}>
<SideMenu
menu={infoText}
menuPosition="right"
disableGestures={true}
isOpen={this.props.rightMenuOpen}
>
<WebView
source={{uri: 'https://www.michigandaily.com/'}}
bounces={false}
/>
</SideMenu>
</View>
);
}
}
您尝试此操作的方式将行不通,因为更改 passProps 的值不会导致重新呈现。您需要的是一种使用事件发射器或状态管理框架将信号从父级传递给子级的方法。
如何使用事件发射器的示例:
https://colinramsay.co.uk/2015/07/04/react-native-eventemitters.html
我还建议使用 状态管理 框架,如 Redux 或 Mobx(我更喜欢 Mobx,因为它的简单性)。
您可以在此处了解有关 Mobx 的更多信息:http://mobx.js.org
当我按下 NavigatorIOS React Native 组件上的通知按钮时,我试图打开一个侧边菜单,但当父组件的状态发生变化时,子组件似乎没有更新。因此,按下通知按钮并没有按照我的意愿进行。父子组件如下。当使用 NavigatorIOS 更改父状态时,如何让子组件更新?
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
rightMenuOpen: false
}
this.rightButtonPress = this.rightButtonPress.bind(this);
}
rightButtonPress() {
this.setState({rightMenuOpen: true});
}
render() {
return (
<NavigatorIOS
initialRoute={{
component: Home,
rightButtonIcon: source=require('./img/notifications.png'),
onRightButtonPress: this.rightButtonPress,
passProps: {index: 1, rightMenuOpen: this.state.rightMenuOpen},
}}
style={{flex: 1}}
/>
)
}
}
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
const menu = <Switch/>
return (
<View style={styles.body}>
<SideMenu
menu={infoText}
menuPosition="right"
disableGestures={true}
isOpen={this.props.rightMenuOpen}
>
<WebView
source={{uri: 'https://www.michigandaily.com/'}}
bounces={false}
/>
</SideMenu>
</View>
);
}
}
您尝试此操作的方式将行不通,因为更改 passProps 的值不会导致重新呈现。您需要的是一种使用事件发射器或状态管理框架将信号从父级传递给子级的方法。
如何使用事件发射器的示例: https://colinramsay.co.uk/2015/07/04/react-native-eventemitters.html
我还建议使用 状态管理 框架,如 Redux 或 Mobx(我更喜欢 Mobx,因为它的简单性)。
您可以在此处了解有关 Mobx 的更多信息:http://mobx.js.org