首页 > 解决方案 > 用useEffect显示模态的方法是什么?

问题描述

我使用时无法显示模态的原因是什么useEffect?我的代码有什么问题,如何修复它以在我的示例中显示我想要的模式?在我的示例中,我只是具有noItemsModal()我希望它在以下情况下工作的功能useEffect

function tabol({ paramsList = { list: [] } }) {
  const [modalVisible, setModalVisible] = useState(false);

 function noItemsModal() {
    <View style={styles.centeredView}>
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert('Modal has been closed.');
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello World!</Text>

            <TouchableHighlight
              style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
              onPress={() => {
                setModalVisible(!modalVisible);
              }}
            >
              <Text style={styles.textStyle}>Hide Modal</Text>
            </TouchableHighlight>
          </View>
        </View>
      </Modal>
    </View>;
setModalVisible(true);
  }

  ////////

  useEffect(() => {
    if (dataList == 0) {
      noItemsModal();
    }
  }, []);
}

标签: javascriptreactjsreact-nativereact-hooks

解决方案


我猜你是 React Native 的新手 :) 首先,你的组件需要留在主返回函数中。您需要做的就是改变modalVisible状态。它会自己出现和消失。您不应该调用整个组件本身。它应该保留在主返回或渲染函数中,并且只有 modalVisible 状态会重新渲染自身。

这是基本示例:

https://github.com/WrathChaos/react-native-modal-example

跑步

  • npm i
  • react-native run-ios/android

推荐阅读