React Native:模态问题 - 按下按钮时模态未关闭

问题描述 投票:0回答:1

我目前在 React Native 项目中遇到与 Modal 组件相关的问题。尽管设置了一个按钮来关闭模式,但它并没有按预期工作。这是我的代码的简化版本:

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

export default function MyComponent() {
  const [isModalVisible, setModalVisible] = useState(false);

  const handleOpenModal = () => {
    setModalVisible(true);
  };

  const handleCloseModal = () => {
    setModalVisible(false);
    console.log('Modal closed!');
  };

  return (
    <View>
      <Button title="Open Modal" onPress={handleOpenModal} />
      <Modal visible={isModalVisible} animationType="slide">
        <View>
          <Text>Modal Content</Text>
          <Button title="Close Modal" onPress={handleCloseModal} />
        </View>
      </Modal>
    </View>
  );
}

尽管有handleCloseModal 函数,按下“关闭模态”按钮并不会按预期关闭模态。函数内部的日志语句也不会出现在控制台中。

有人可以提供指导,指导如何排查和解决 React Native 中按下按钮时 Modal 未关闭的新问题吗?任何见解或建议将不胜感激。谢谢!

javascript react-native
1个回答
0
投票

试试这个:

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

export default function MyComponent() {
  const [isModalVisible, setModalVisible] = useState(false);

  const handleOpenModal = () => {
    setModalVisible(true);
  };

  const handleCloseModal = () => {
    setModalVisible(false);
    console.log('Modal closed!');
  };

  return (
    <View>
      <Button title="Open Modal" onPress={handleOpenModal} />
      {isModalVisible && <Modal visible={isModalVisible} animationType="slide">
        <View>
          <Text>Modal Content</Text>
          <Button title="Close Modal" onPress={handleCloseModal} />
        </View>
      </Modal>
     }
    </View>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.