Props
props allow you to pass data from a parent (wrapping) component to a child (embedded) component.
const posts = () => {
return (
<div>
<Post title="My first Post" />
</div>
);
}
Here,title is the custom property(prop) set up on the custom Post component.
const post = (props)=>{
return (
<div>
<h1>{props.title}</h1>
</div>
)
};
The Post componet recieves the props argument. You can of course name this argument whatever you want - it id your function definition,React does not care!But React will pass one argument to your componet function => An object, which contains all properties you set up on <Post ... /> . {props.title} then dynamically outputs the title property of the props object - which is available since we set the title property inside AllPosts component (see above).
State
Whilst props allow you to pass data down the component tree (and hence trigger an UI update), state is used to change the component, well, state from within. Changes to state also trigger an UI update.
class NewPost extends Component { // state can only be accessed in class-based components!
state = {
counter: 1
};
render () {
//Needs to be implemented in class-based components! Needs to return some JSX!
return (
<div>{this.state.counter}</div>
);
}
}
Here, the NewPost component contains state . Only class-based components can define and use state . You can of course pass the state down to functional components, but these then can't directly edit it. state simply is a property of the component class, you have to call it state though - the name is not optional. You can then access it via this.state in your class JSX
code (which you return in the required render() method). Whenever state changes (taught over the next lectures), the component will re-render and reflect the new state. The difference to props is, that this happens within one and the same component - you don't receive new data (props ) from outside!
Difference between State and Props
State是可变的,是组件内部维护的一组用于反映组件UI变化的状态集合;而Props对于使用它的组件来说,是只读的,要想修改Props,只能通过该组件的父组件修改。在组件状态上移的场景中,父组件正是通过子组件的Props, 传递给子组件其所需要的状态.
Define State
组件中用到的一个变量是不是应该作为组件State,可以通过下面的4条依据进行判断:
- 这个变量是否是通过Props从父组件中获取?如果是,那么它不是一个状态。
- 这个变量是否在组件的整个生命周期中都保持不变?如果是,那么它不是一个状态。
- 这个变量是否可以通过其他状态(State)或者属性(Props)计算得到?如果是,那么它不是一个状态。
- 这个变量是否在组件的render方法中使用?如果不是,那么它不是一个状态。这种情况下,这个变量更适合定义为组件的一个普通属性,例如组件中用到的定时器,就应该直接定义为this.timer,而不是this.state.timer。