在 React Native 中更改其 class 之外的模式小部件的状态

Change state of modal widget outside its class in React Native

我有两个不同的文件:HomeScreen.jsModalWidget.js。第二个文件包含模态对话框 window 的实现,我需要通过单击主屏幕上的按钮来调用此小部件。此外,此模式必须能够通过其上的按钮自行关闭。我尝试使用全局状态挂钩,但它给了我一条错误消息:Invariant Violation: Invalid Hook call。那么,如何从主屏幕调用此模态?

ModalWidget.js

import React, { useState } from 'react';
import { Text, Button, Modal } from 'react-native';

export function ModalWidget(modalState) {

  const [modalVisible, setModalVisible] = useState(modalState);

  return (
    <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
      >
      <Button
        title="Close"
        onPress={setModalVisible(false)}
      />
    </Modal>

  )
};

HomeScreen.js

import React, { useState } from 'react';
import { Text, View } from 'react-native';
import { ModalWidget } from '../components/ModalWidget';

export default function HomeScreen() {

  const [modalState, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <ModalWidget
        state={modalState}
      />
      <Button
        title="Open"
        onPress={setModalVisible(true)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

尝试将函数作为 prop 传递,并在 HomeScreen 中传递。 HomeScreen.js

<ModalWidget
  state={modalState}
  onPress={closeModel}
/>

closeModel(){
  setModalVisible(true)
}

ModalWidget.js

<Modal
  animationType="slide"
  transparent={true}
  visible={modalVisible}
>
  <Button
    title="Close"
    onPress={props.onPress()}
  />
</Modal>

此外,您不能在函数组件中访问状态。