我正在尝试制作一个自定义复选框组件(实际上是一个三态组件,但这无关紧要,只是说我不只是使用输入),并且我不确定如何使其能够更改自身点击和来自父级的值集的“检查性”。
目前,我让它作为一个自给自足的组件工作,它采用 onChange 属性和处理程序回调,它在单击后调用将值发送给父组件。它使用状态来存储选中状态,并由显示引用。
如果它只是检查性的显示,并且值(value)是从外部管理的,那么我自然会使用 props。如果它只是一个自给自足的复选框组件,它接受一个初始值,然后只响应点击,我会像我一样使用状态,但我的问题是我希望它可以点击来打开和关闭自己,并且也允许家长打开和关闭它。
我是 React 和“React 思维方式”的初学者,所以我怀疑我的做法是错误的。我的印象是,执行此操作的正确方法是使其成为一个仅显示组件,将点击传递给父级进行处理,然后从父级接收值更改的 Prop 更新,但是在我看来,这将使组件的可重用性大大降低。
那么我该如何从内部和父来源更改复选框呢?
也欢迎提供相关链接。
最佳答案
您可以将复选框视为dumb组件,这意味着它不保存任何内部状态,而仅通过props从外部接收数据,然后渲染他们。可以查看dumb组件的详细定义here .
同时,当单击复选框时,此类事件将由组件的父级或事件祖先处理,这称为反向数据流,在 Facebook 的 Thinking in React 中进行了描述。 博客文章。
此外,为了决定哪个组件应保持某些状态,我发现以下准则非常有用:
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand, so follow these steps to figure it out:
For each piece of state in your application:
- Identify every component that renders something based on that state.
- Find a common owner component (a single component above all the components that need the state in the hierarchy).
- Either the common owner or another component higher up in the hierarchy should own the state.
- If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
伪代码片段:
const Checkbox = React.createClass({
// Propagate the event to parents
onClick(evt) {
if (this.props.handleClick) {
this.props.handleClick({checked: evt.target.value});
}
},
render() {
return (
this.props.checked ?
<Input onClick={this.onClick} type="checkbox" label="Checkbox" checked></Input> :
<Input onClick={this.onClick} type="checkbox" label="Checkbox"></Input>
);
}
});
const Container = React.createClass({
handleClick(evt) {
// Change the container's state, which eventually changes the checkbox's view via props.
this.setState({checked: evt.checked});
},
render() {
return (
<div><Checkbox checked={this.state.checked} handleClick={this.handleClick}></Checkbox></div>
);
}
});
关于reactjs - 如何管理 React 组件上的状态,该组件的状态可以从父级或其上的事件更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361583/