Props

props 讓你能夠從 parent component pass data 到 child component.
以下舉幾個pass的例子,以functional programming為例

‘’’=javascript
const passData = () => {
return (




);
}
‘’’
在上面的範例中,title是自定義的prop
可以想像一下,很像HTML attribute
此外,也可以pass method到child

‘’’=html

‘’’

‘’’=javascript
const passData = (props) => {
return (


{props.title}



);
}
‘’’
passData component收到props argument,當然你可以命名成你習慣的名稱。
但是react只能pass一個argument到你的component function

State

State扮演著改變component的角色
同時,改變State也會trigger到UI的更新
‘’’=javascript
class Post extends Component {
state = {
counter: 1
};

render () {
    return (
        <div>{this.state.counter}</div>
    );
}

}
‘’’
這邊需要注意的地方是,只有class based的component才可以使用state。
你也可以pass state到child的functional component
當改變了state之後,component將會re-render,state也會reflect新的state

兩者差異

allow you to pass data from a parent (wrapping) component to a child (embedded) component.


Comment