首页 > 解决方案 > 如何使用从另一个文件导入的功能组件在 React Native 中显示模态

问题描述

我正在显示一个视图 Login.js,在该视图中单击按钮,我需要呈现模态,我已将其分离并写入另一个名为 Country.js 的文件中。

在 Login.js 文件上,我导入了 Country.js 并单击按钮,我正在这样做:

show_modal = () => {
    <Countries/>
}

但什么都没有发生。我是一个菜鸟,我刚开始 React Native,请帮助我。

Country.js 代码:

import React, { Component, useState } from "react";
import {
Alert,
Modal,
Text,
TouchableHighlight,
View
} from "react-native";

const Countries = () => {

    console.log('called');
    
    const [modalVisible, setModalVisible] = useState(true);
    
    return (
    
    <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>
    
      <TouchableHighlight
        style={styles.openButton}
        onPress={() => {
          setModalVisible(true);
        }}
      >
        <Text style={styles.textStyle}>Show Modal</Text>
      </TouchableHighlight>
    </View>)
};
    
export default Countries;

标签: reactjsreact-nativejsx

解决方案


登录.js

import React, { Component, useState } from "react";
import {Modal, View, Text, TouchableHighlight} from 'react-native';
import CountryModal from 'path to outsource country modal file';

const login = (props)=>{
const [modalVisible, setModalVisible] = useState(true);

return(

<View>
    <TouchableHighlight
style={styles.openButton}
onPress={() => {
    setModalVisible(true);
}}
>
<Text style={styles.textStyle}>Show Modal</Text>
</TouchableHighlight>

<CountryModal isVisible={modalVisible} setModalVisiblity = {()=>{setModalVisible(preState=> preState = !preState)}}>
</View>
)
}

export default login;

国家模式文件

import React from react;
import {Modal} from 'react-native';

const Country = (props)=>{

return (
<Modal
    animationType="slide"

    transparent={true}
    visible={isVisible}
    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={() => {props.setModalVisiblity
          }}
        >
          <Text style={styles.textStyle}>Hide Modal</Text>
        </TouchableHighlight>
      </View>
    </View>
  </Modal>
)
}

希望你得到你的答案。


推荐阅读