首页 > 解决方案 > 在不卸载子组件的情况下切换 React 父组件

问题描述

我希望在不卸载包含的子类的情况下将父组件从更改<View /><SafeAreaView />

// App

<SafeView>
  <MainNavigator />
</SafeView>

// SafeView component

class SafeView extends React.Component<Props> {
  render() {
    const { children, showSafeView } = this.props;
    const Component = showSafeView ? SafeAreaView : View;
    return (
      <Component style={styles.view} key="test_component">
        <View style={{ flex: 1 }} key="test_view">
          { children }
        </View>
      </Component>
    );
  }
}

const mapStateToProps = state => ({ showSafeView: state.navigation.safe });

export default connect(mapStateToProps)(SafeView);

观察到的行为是:

  1. “showSafeView 道具更新
  2. 父组件发生变化
  3. 子组件卸载
  4. 子组件挂载

您可以看到我正在使用props.children,但我也尝试将子组件直接作为道具传递,结果相同:

<SafeView Child={MainNavigator} />

///

const { Child, showSafeView } = this.props;
const Component = showSafeView ? SafeAreaView : View;
return (
  <Component style={styles.view} key="test_component">
    <View style={{ flex: 1 }} key="test_view">
      <Child key="test_child" />
    </View>
  </Component>

标签: reactjsreact-nativeredux

解决方案


推荐阅读