首页 > 解决方案 > 如何在react-native中显示从另一个js文件到当前文件的模式?

问题描述

我想显示从另一个 js 类到当前类文件的模态。我可以在当前 js 文件中将模态可见性设置为真,因此我的模态代码位于另一个类中。我想在实际注册类中使用此代码。这里是我的代码:-

CountryCodePicker.js

  import React, { Component } from 'react';
  import { StyleSheet,  Text,  View} from 'react-native'
  import { showMessage } from '../utils/GeneralFunctions';
  import { countryPicker } from './CountryPickerModal';

  export default class CountryCodePicker extends Component {    
      constructor(props) {
      super(props)

      }

    render() {
      return (
          <View style={styles.container}>
              <Text
                  onPress={() => {
                    <countryPicker modalVisible={true}/>
                  }} 
                  style={styles.welcome}>Open Modal</Text>
          </View>
      );
    }
  }


  const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
        padding:20
      }
    })

CountryPickerModal:这是我想在国家选择器类上显示的模式代码。

  import React from 'react';
  import {Modal,View,Text} from 'react-native';
  import { showMessage } from '../utils/GeneralFunctions';

  export const countryPicker = (props) => {
      const {modalVisible = false} = props;

      state = {
          modalVisible:modalVisible
      }

      showModal = () => {
          // if(modalVisible == false){
          //     modalVisible = true;
          // }else{
          //     modalVisible=false;
          // }

          this.setState({modalVisible:true});
      }

      return(
          <Modal
              visible={modalVisible}
              animationType='slide'
              transparent={false}
              onRequestClose={() => {showMessage('Closed')}}
          >
          <View>
              <Text 
                  style={{fontSize:24,fontWeight:'900',padding:16}}
                  onPress={() => {showMessage("Country Picker 
                          Modal")}}
              >
                  Close Modal
              </Text>
          </View>
          </Modal>
      )
  }

标签: javascriptnode.jsreact-nativeecmascript-6

解决方案


定义它render并传递标志以显示或隐藏。

render() {
  return (
      <View style={styles.container}>
          <Text
              onPress={() => {
                this.setState({modalVisible:true})
              }} 
              style={styles.welcome}>Open Modal</Text>
          <countryPicker modalVisible={this.state.modalVisible}/>          
      </View>
  );
}

推荐阅读