在不卸载子组件的情况下切换React父组件

时间:2019-10-07 11:03:14

标签: reactjs react-native redux

我希望在不卸载包含的子类的情况下将父组件从<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>

0 个答案:

没有答案