React Native之导出

1 React Native里面一般导出函数或者常量或者组件

如果是默认组件或者类(export default修饰)的话,在另外一个地方导入的时候不需要加上{},格式如下
  导出

  export default class Student {
  }

导入

 import Student from "./file"

如果不是默认组件或类或则方法或则变量(没有用default修饰)的话,在另外一个地方导入的时候需要加上{},格式如下
  导出:使用module.exports

  module.exports = {fun1, fun2, 常量}

导入

 import {xxx2, xxx2, ...} from "./file"

好处:在另外一个文件地方导入了,就可以使用导入的函数或者变量或者组件,非常方便,相当于java里面的import导入类文件一样.

还可以是用一个变量,然后变量里面放键值对数组,key是函数名字,value是函数实现

如下

let fun = {fun1 : (a, b) => {return a + b}, fun2 : (a, b) => {return a - b}} 

export default fun;

2 简单测试

Student.js文件如下

'use strict';

import React from 'react'

class Student {
    constructor(name: string) {
this.name = name;
    }
    _getName = () => {
console.log("_getName");
return this.name;
    };
}

export default Student

Fun.js文件如下

'use strict';

import React from 'react'

const sum = (a, b) => {
return a + b;
}

const sub = (a, b) => {
return a - b;
}

const myName = 'chenyu';

module.exports = {
sum,
sub,
myName
}

Fun_second.js文件如下

'use strict';

import React from 'react'

//我们把所有的函数放在一个变量里面,这个变量里面放的都是键值对,
//然后key是函数名字,value是我们函数实现
let fun = {  //记得这是是let fun = { },不是let fun {}
//相加函数
sum : (a, b) => {
    return a + b;
},
//相减函数
sub : (a, b) => {
return a - b;
}
}

export default fun;

App.js文件如下

import React from 'react';
import {View, Text} from 'react-native';
import {DeviceEventEmitter} from "react-native";

import Student from "./Student"
import {sub, sum, myName} from "./Fun"
import fun from "./Fun_second"

export default class App extends React.Component {

       constructor(props) {
          super(props);
          this.state = {
name: '点击我',
sumRes: 'sumRes',
subRes: 'subRes',
stuName: 'hello',
sumRes_sec: 'sumRes_sec',
subRes_: 'subRes_'
  };
       }

       render() {
          return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
              <Text
          onPress={() => this._press(5, 2)}
               >{this.state.name}</Text>

              <Text>{this.state.sumRes}</Text>
              <Text>{this.state.subRes}</Text>
              <Text>{this.state.stuName}</Text>
              <Text>{this.state.sumRes_sec}</Text>
              <Text>{this.state.subRes_}</Text>
            </View>
          );
       }

   _press = (a, b) => {
   this.setState({name: myName});
   let res = sum(a, b);
   console.log("res is:" + res);
   this.setState({sumRes : res});
   let res1 = sub(a, b);
   console.log("res1 is:" + res1);
         this.setState({subRes : res1});
   let student = new Student("chengongyu");
   let studentName = student._getName();
   this.setState({stuName : studentName});
   let sumSec = fun.sum(4, 9);
   this.setState({sumRes_sec : sumSec});
   let subSec = fun.sub(10, 2);
   this.setState({subRes_: subSec});
  }

}

  

3 运行结果

点击 '点击我'之后效果如下

(0)

相关推荐