【问题标题】:React Native - How to create and render a component on top of other componentsReact Native - 如何在其他组件之上创建和渲染组件
【发布时间】:2018-02-02 16:18:57
【问题描述】:

我正在使用 RN 0.47,我正在尝试构建一个组件,我可以将消息 (prop) 传递给该组件并将其呈现在当前显示组件的顶部,其功能类似于提供的 Alert API,但是我想要以不同的方式对其进行样式和定位。

我正在使用 React Navigation 创建 TabNavigator 视图,因此我将在多个选项卡/模块中调用该组件。

这是我的模态代码

import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View } from 'react-native';

    class ModalView extends Component {

      state = {
        modalVisible: true,
      }

      setModalVisible(visible) {
        this.setState({modalVisible: visible});
      }

      render() {
        return (
          <View style={{marginTop: 22}}>
            <Modal
              animationType={"slide"}
              transparent={false}
              visible={this.state.modalVisible}
              onRequestClose={() => {alert("Modal has been closed.")}}
              >
             <View style={{marginTop: 22}}>
              <View>
                <Text>Hello World!</Text>

                <TouchableHighlight onPress={() => {
                  this.setModalVisible(!this.state.modalVisible)
                }}>
                  <Text>Modal</Text>
                  <Text>is</Text>
                  <Text>displayed</Text>
                </TouchableHighlight>

              </View>
             </View>
            </Modal>
          </View>
        );
      }
    }

    export default ModalView;

这是网络获取失败时调用Modal的函数的代码

import React from 'react';
import {ToastAndroid,Alert,Platform} from 'react-native';
import ModalView from "./Modal"

module.exports = async function(url, cb) {
  try {
    //do something

  } catch(error) {
    Platform.OS == "ios"?
      <ModalView />
      :
      ToastAndroid.show(error.toString(), ToastAndroid.LONG)
  }
}

最后,上面的函数在 react-navigation 选项卡组件的 componentDidMount 函数中被调用和执行,但模态永远不会显示。

【问题讨论】:

    标签: javascript reactjs react-native render


    【解决方案1】:

    显然,您需要一个 Modal:
    https://facebook.github.io/react-native/docs/modal.html

    但是,如果你需要更通用的东西,你可以使用position: 'absolute' 样式,结合toprightbottomleft 样式。

    【讨论】:

    • 我在单独的文件中制作了模态组件,并调用它从另一个文件中渲染,就像 一样,但没有渲染。关于它为什么不起作用的任何线索?
    • 你在添加道具visible={true}吗?你能粘贴你的代码吗?
    • 我做了,我将在另一个问题中发布代码。谢谢
    • 抱歉花了一段时间,但我已经添加了我的代码,但模态仍然没有呈现。
    猜你喜欢
    • 2020-09-13
    • 2021-08-25
    • 2016-06-06
    • 2018-02-17
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多