0
点赞
收藏
分享

微信扫一扫

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

举报

相关推荐

0 条评论