Props and state are related.(道具和状态有关。)
The state of one component will often become the props of a child component.(一个组件的状态通常会成为子组件的道具。) Props are passed to the child within the render method of the parent as the second argument to React.createElement()
or, if you're using JSX, the more familiar tag attributes.(道具作为React.createElement()
的第二个参数传递给父对象的render方法中的子对象,或者,如果您使用的是JSX,则将其作为更熟悉的标签属性。)
<MyChild name={this.state.childsName} />
The parent's state value of childsName
becomes the child's this.props.name
.(父级的childsName
状态值成为子级的this.props.name
。)
From the child's perspective, the name prop is immutable.(从孩子的角度来看,prop这个名字是一成不变的。) If it needs to be changed, the parent should just change its internal state:(如果需要更改,则父级只需更改其内部状态即可:)
this.setState({ childsName: 'New name' });
and React will propagate it to the child for you.(React将为您将其传播给孩子。)
A natural follow-on question is: what if the child needs to change its name prop?(接natural而来的自然问题是:如果孩子需要更改道具名称该怎么办?) This is usually done through child events and parent callbacks.(这通常是通过子事件和父回调完成的。) The child might expose an event called, for example, onNameChanged
.(子级可能会公开一个事件,例如onNameChanged
。) The parent would then subscribe to the event by passing a callback handler.(然后,父级将通过传递回调处理程序来订阅事件。)
<MyChild name={this.state.childsName} onNameChanged={this.handleName} />
The child would pass its requested new name as an argument to the event callback by calling, eg, this.props.onNameChanged('New name')
, and the parent would use the name in the event handler to update its state.(子级将通过调用例如this.props.onNameChanged('New name')
来将其请求的新名称作为参数传递给事件回调,而父级将在事件处理程序中使用该名称来更新其状态。)
handleName: function(newName) {
this.setState({ childsName: newName });
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…