美文网首页React Native开发经验集React Native开发
React Native学习笔记(六)-state和props

React Native学习笔记(六)-state和props

作者: Nickyzhang | 来源:发表于2017-05-04 21:18 被阅读321次
  • props(属性):是由父组件传递给子组件的,而且是单向的传递属性,当属性多的时候可以进行对象的传递
  • state(状态):是组件内部维护的数据,当状态发生变化时,组件就会更新,界面就会随着state的变化而重新渲染

在ES6风格定义props和state

定义props
static defaultProps={
    name:'Cral',
    age:25
}
定义state
constructor(props) {
  super(props);
  this.state = {name:'Gates'};
}
Props:组件间的状态传递
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class Greeting extends Component {
  render() {
    return (
      <Text>Hello {this.props.name}!</Text>
    );
  }
}

class HelloWorld extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}

AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

定义了Greeting组件,该组件设置了属性name,父组件在调用Greeting组件是将属性name传递过去,子组件就会显示相应的内容。
React Native是组件化的,这里把需要的两个组件写在了一起,可以更直观的感受到数据的传递。

state:组件内的状态改变
import React, {Component} from 'react';

import Child from './components/child'
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {name: 'child'};
        this.dataChange = this.dataChange.bind(this);
    }

    dataChange(){
        this.setState({name: 'newChild'})
    }
    render() {
        return (
            <div style={{textAlign:'center'}}>
                <Text OnClick={this.dataChange}>{this.state.name} </Text>
            </div>
        );
    }
}

export default App;

在组件内部可以通过state来设置组件的初始值,当组件的数据需要变化时可以通过设置setState方法来重新渲染组件自己

相关文章

网友评论

    本文标题:React Native学习笔记(六)-state和props

    本文链接:https://www.haomeiwen.com/subject/bqidtxtx.html