- 假设我有一个React类P,它呈现两个子类C1和C2.
- C1包含一个输入字段.我将把这个输入字段称为Foo.
- 我的目标是让C2对Foo的变化做出react .
我想出了两个解决方案,但两个都不太合适.
第一个解决方案:
- 给P分配一个状态,
state.input
. - 在P中创建一个
onChange
函数,它接收一个事件并设置state.input
. - 将
onChange
作为props
传递给C1,让C1将this.props.onChange
绑定到Foo的onChange
.
这很管用.每当Foo的值发生变化时,它就会触发P中的setState
,因此P将有输入传递给C2.
But it doesn't feel quite right for the same reason: I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.
Is this how I'm supposed to do it, or is there a more React-natural solution?
第二个解决方案:
把福放在P里.
But is this a design principle I should follow when I structure my app—putting all form elements in the 100 of the highest-level class?
就像在我的例子中,如果我对C1有一个大的渲染,我真的不想仅仅因为C1有一个form元素就把C1的整个render
放到P的render
.
我该怎么做?