在 React 中,数据是自顶而下单向流动的,即从父组件到子组件。
React的数据传输主要靠state和props来完成。如果顶层组件初始化 props,那么 React 会向下遍历整棵组件树,重新尝试渲染所有相关的子组件。state 只关心每个组件自己内部的状态,这些状态只能在组件内变化。把组件看成一个函数,那么它接收了 props 作为参数,内部由 state 作为函数的内部参数,返回一个 Virtual DOM 的实现。
state
state中往往储存一些时刻变化的变量或者后期可能要更新的参数。我们用setState()方法来更新state中的值。
下面是一个计数的例子,通过点击更新按钮,触发setState()方法,使state中的值发生改变。
import React, {Component} from 'react';
class Counter extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.state = {
count: 0,
}
}
handleClick(e) {
e.preventDefault();
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.handleClick}>更新</button>
</div>
)
}
}
export default Counter
props
props往往用来定义一些静态的常量,或者用于父子组件间的通信。props本身是不可变的,当我们试图改变props中的原始值,React会报出类型错误的警告。
import React, {Component} from 'react';
class Props extends Component {
static defaultProps = {
name: 'everybody'
}
render() {
return (
<div>
<h1>Hello, {this.props.name}</h1>
</div>
)
}
}
export default Props
网友评论