通常在开发中,State和Props是一起使用的。

有以下注意点:

1-:State属性属于组件内部,不能垮组件使用,值只能在本组件内进行修改,修改时使用setState;

2-:Props对于使用的组件来说使用外部属性。不能在使用组件内部进行修改,值的修改只能在组件外部进行修改,修改时,只能修改props的‘源’。

3-:某些情况下,State和Props是一一对应的,当修改State时,也会修改Props;

4-:使用一次setState,页面执行一次"render函数",万物即State,所以,当想要页面上的组件,属性等修改时,则操作state即可。

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

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

export default class LearnDay extends Component {
  constructor(props){
    super(props);
    this.state={
      msg:'Hello World',
    }
  }


  render() {
    return (
      <View style={styles.container}>
        <View style={{alignItems: 'center'}}>
          <Greeting name={this.state.msg} />
          <Greeting name='Hello' />
          <Greeting name='Hello Msg' />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

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

在LearnDay中,第一个Greeting的name属性值,是通过LearnDay中的state进行获得的。

results matching ""

    No results matching ""