React Native之最构建对象通过构造方法传递值然后再获取值

1 问题

在一个文件构建一个对象,然后在另外一个文件里面new这个对象,通过构造方法传递参数,然后再获取这个参数

2 测试代码

Student.js文件如下

    'use strict';
     
    import React from 'react'
     
    import {NativeModules, NativeEventEmitter, DeviceEventEmitter,Alert} from 'react-native'
     
    class Student {
        constructor(name: string) {
        this.name = name;
        }
        _getName = () => {
        console.log("_getName");
        return this.name;
        };
    }
     
    export default Student

这里我们可以直接在构造方法里面写this.name,而且不需要声明,但是在java里面肯定是要声明 name才行.

App.js文件如下

    import React from 'react';
    import {View, Text} from 'react-native';
     
    import Student from "./Student";
     
    export default class App extends React.Component {
            
           constructor(props) {
              super(props);
              this.state = {name: '点击我'};
           }
     
           render() {
              return (
                <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                  <Text
                  onPress={() => this._press()}
                   >{this.state.name}</Text>
                </View>
              );
           }
     
           _press = () => {
               console.log("HomeScreen press");
               let student = new Student("chenyu");
               let StudentName = student._getName();
           console.log("name is:" + StudentName);
           this.setState({name: StudentName});
           }
    }

更多请见:http://www.mark-to-win.com/tutorial/51882.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值