2.4 Props & States

1.props: properties are passed to a component and can hold any data

  1. class User extends Component {
  2. render(){
  3. const user = this.props.data;
  4. this.props.onReady('I am ready!');
  5. return(
  6. <View>
  7. <Text>
  8. score: {this.props.score}
  9. type: {this.props.type}
  10. Name: {user.name}
  11. Age: {user.age}
  12. </Text>
  13. </View>
  14. );
  15. }
  16. }
  17. //dufaultProps
  18. User.propTypes = { score: React.PropTypes.number };
  19. User.defaultProps = { score: 0 };
  20. var user = {name: 'foo', age: 21};
  21. class Main extends Component {
  22. handleReady(str){
  23. console.log(str);
  24. }
  25. render(){
  26. return(
  27. <View>
  28. <User type="Dev" data={user} onReady={this.handleReady}/>
  29. </View>
  30. );
  31. }
  32. }

2.state: State differs from props in that it is internal to the component.

  1. class Timer extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {count: 0};
  5. }
  6. componentDidMount() {
  7. let that = this;
  8. setInterval(function () {
  9. that.increase();
  10. }, 1000);
  11. }
  12. increase() {
  13. this.setState({count: this.state.count + 1});
  14. }
  15. render() {
  16. return (
  17. <View>
  18. <Text>count: {this.state.count}</Text>
  19. </View>
  20. );
  21. }
  22. }
  23. class Main extends Component {
  24. render(){
  25. return(
  26. <View>
  27. <Timer/>
  28. </View>
  29. );
  30. }
  31. }

3.props VS state

  • Use props to pass data and settings through the component tree.
  • Never modify this.props inside of a component; consider props immutable.
  • Use props to for event handlers to communicate with child components.
  • Use state for storing simple view state like wether or not drop-down options are visible.
  • Never modify this.state directly, use this.setstate instead.
     2.4 Props & States  - 图1

4.Stateless Component

  1. const Heading = ({title}) => <Text>{title}</Text>;
  2. ..
  3. ...
  4. <Heading title="test title"/>
  5. ...
  6. ..

原文: https://unbug.gitbooks.io/react-native-training/content/23states&_props.html