【问题标题】:How to include view to component from another file in react native?如何在本机反应中包含来自另一个文件的组件视图?
【发布时间】:2018-07-05 05:40:44
【问题描述】:

我有以下课程,我如何在 php 中包含另一个文件中的视图,例如 include()。

class A extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>A</Text> 
      </View>
    );
  }
}

class B extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>B</Text>
      </View>
    );
  }
}

class C extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>B</Text>    
      </View>
    );
  }
}

我必须包含来自外部文件的视图。我们可以通过导入将一个类包含到另一个类中,但是视图呢?

【问题讨论】:

  • 你能清楚你应该做什么吗?您想在第三个组件中显示component Acomponent B 吗?或Component AComponent Binclude是什么意思
  • 组件 a,b,c 中的所有视图都想添加到另一个文件中,并像 php 中的 include() 一样包含在此处
  • 我觉得includeimport很像

标签: class react-native import view include


【解决方案1】:

基本上,您有一个关于导入文件的问题。 考虑三件事,

  • 导出

    您可以export 多个 const or class 并在导入语句中使用{} 导入它们。

  • 导出默认值

    export default 使用的关键字从文件中导出 constclass。导出默认仅适用于一个文件

  • 导入

    import 关键字用于导入导出的文件,文件路径后跟from关键字

    import ExportWithDefault, {ExportWithOutDefault} from './fileName.js'

参考:importexport, export default

让我们考虑只导出为export 的组件A,B,C 文件comps.js。 喜欢

//file comp.js


 import React,{Component} from 'react'
 import {View, Text} from 'react-native'
   export class A extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>A</Text> 
      </View>
    );
  }
}

导出类 B 扩展组件 { 使成为() { 返回 ( 乙 ); } }

export class C extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text>C</Text>    
      </View>
    );
  }
}

现在考虑文件main.js 是您要导入A,B,C 并显示的文件。

import React, { Component} from 'react
import { View} from 'react-native
import {A,B,C} from './comp'; //considering both files in same directory
    class Main extends Component {
       render(){
         return(
         <View>
            <A/>
            <B/>
             <C/>
           </View>
         )
       }
    }

【讨论】:

  • 错误:无法将没有 YogaNode 的子节点添加到没有度量函数的父节点
  • 我以为你已经在 comp.js 中导入了 View and Text 之类的东西
  • 在 comp.js 和 main.js 中导入的视图和文本.. 但在两个文件中都没有导入错误。那怎么办?
  • 我的错误实际上需要在我们在 main.js 中使用 View 的两个文件中导入 View。会更新ans
  • 我们使用了View 组件但忘记导入和反应返回单个元素
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
相关资源
最近更新 更多