首页 > 解决方案 > 创建一个可重用的 React Native 模态组件

问题描述

当我感到不知所措时,我将回到 React Native 的基础知识。我一直在寻找可重用模态组件的实现。我正在寻找 RN 中可重用的模态组件的示例?提前致谢

标签: react-native

解决方案


你可以在 StackOverflow 上找到很多这样的例子。不过,如果您需要示例,我可以为您提供一个示例。您在问题中提到了模态组件,对吗?

您的组件将与道具看起来像这样。让这个文件的名字是 ModalComponent。

render() {
    const { isVisible, message, textValue } = this.props;
    return (
      <Modal
        animationType="slide"
        transparent={false}
        isVisible={isVisible}
        backdropColor={"white"}
        style={{ margin: 0 }}
        onModalHide={() => {}}>
        <View>
          <Text>textValue</Text>
          <Text>message</Text>
        </View>
      </Modal>
    );
  }

所以现在在你的 js 文件中你需要导入这个 modalComponent 之后,你需要写成

  <ModalComponent 
       isVisible={true}
       textValue={'hi there'}
       message={'trying to make a basic component modal'}/>

希望这对你有帮助

编辑:

创建要在模态中呈现的单独组件。例如:component1.js,component2.js,component3.js with props

组件1.js:

render(){
    const { textVal, message } = this.props
    return (
      <View>
        <Text>{textVal}</Text>
        <Text>{message}</Text>
      </View>
    )
  }

现在在 ModalComponent

render() {
  const { first, second, third, isVisible, component1Text, component1Message } = this.props;



  <Modal
      animationType="slide"
      transparent={false}
      isVisible={isVisible}
      backdropColor={"white"}
      style={{ margin: 0 }}
      onModalHide={() => {}}>
      <View>
        {first && <component1
          textValue= component1Text
          message= component1Message />}
        {second && <Component2 />}
        {third && <Component2 />}
      </View>
    </Modal>

这样,您可以在单个模态中实现它。


推荐阅读