【问题标题】:React Native NavigatorIOS Child Component Doesn't Update When Parent State ChangesReact Native NavigatorIOS 子组件在父状态更改时不更新
【发布时间】:2017-09-13 15:27:42
【问题描述】:

当我按下 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>
        );
    }
}

【问题讨论】:

    标签: react-native react-native-ios


    【解决方案1】:

    您尝试这样做的方式不起作用,因为更改 passProps 的值不会导致重新渲染。您需要一种使用事件发射器或状态管理框架将信号从父级传递给子级的方法。

    如何使用事件发射器的示例: https://colinramsay.co.uk/2015/07/04/react-native-eventemitters.html

    我还建议使用像 Redux 或 Mobx 之类的 状态管理 框架(我更喜欢 Mobx,因为它很简单)。

    您可以在此处了解有关 Mobx 的更多信息:http://mobx.js.org

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2021-07-17
      • 1970-01-01
      • 2015-08-24
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多