props和state的区别

props:一般用于父组件向子组件通信,在组件之间通信使用。

state:一般用于组件内部的状态维护,更新组建内部的数据,状态,更新子组件的props等。

props 是在组件创建时就传入的数据,是不可变的。
state 是组件可变的数据。

React基于状态实现对DOM控制和渲染;组件状态分为两种;

1:组件间的状态传递;(props) props从父组件到子组建的数据传递

2:组件的内部状态;    (state)  state只能定义在组件内部;定义组件的自己的状态

示例:

'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View
} from 'react-native';

class Hello extends Component {
  render() {
    return (
      <View>
          <Text>{ this.props.title}</Text>
          <Text>{ this.props.text}</Text>
      </View>
    );
  }
}
class HelloComponent extends React.Component{
    constructor (props) {
      super(props);
      this.state = {
         appendText: ''
      };
    }
    _setText() {
       this.setState({appendText: ' Native!'});
    }
    render() {
       return (
         <View>
           <Text onPress={this._setText.bind(this)}>
               {this.props.text + this.state.appendText}
           </Text>
         </View>
       );
    }
}
class learn01 extends Component {
  render() {
    const pros = {
       text: 'hi',
       title: 'title'
    }
    return (
      <View>
          <View style={{height:30}} />
          <Hello {...pros} />
          <HelloComponent text="React"/>
      </View>
    );
  }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值