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 };

21. var user = {name: 'foo', age: 21};
22. class Main extends Component {
23. handleReady(str){
24. console.log(str);
25. }
26. render(){
27. return(
28. <View>
29. <User type="Dev" data={user} onReady={this.handleReady}/>
30. </View>
31. );
32. }
33. }

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. }

7. componentDidMount() {
8. let that = this;
9. setInterval(function () {
10. that.increase();
11. }, 1000);
12. }

14. increase() {
15. this.setState({count: this.state.count + 1});
16. }

18. render() {
19. return (
20. <View>
21. <Text>count: {this.state.count}</Text>
22. </View>
23. );
24. }
25. }

27. class Main extends Component {
28. render(){
29. return(
30. <View>
31. <Timer/>
32. </View>
33. );
34. }
35. }

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>;

3. ..
4. ...
5. <Heading title="test title"/>
6. ...
7. ..

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