我有一个父母类组件,该组件应处理孩子的组件onChange
事件。这是这样做的类方法:
editTopic(index, value) {
this.setState(prevState => {
const class = {...prevState.class};
class.topic =
[...class.topic.slice(0, index), value, ...class.topic.slice(index +1)];
const newClass = {...prevState.class, class};
return {class: newClass};
})
}
我将这种方法作为道具传递给这样的第一个孩子:
editTopic={(index, value) => this.editTopic(index, value)}
我一直向下传递此支架,一直到我可以获得index
的儿童组件。在那里,我正在使用此功能这样的回调将其提供给index
,然后将其传递给select
组件,该组件将给它一个value
:
<AutocompleteSelect handleChange={() => editTopic(index)}/>
和AutocompleteSelect
组件中我在onChange
处理程序中使用此回调:
onChange={(event) => this.props.handleChange(event.target.value)}
但是,这是不起作用的,我应该如何正确地通过此类道具,而不要使AutocompleteSelect
组件知道应该通过哪个index
?
update
我已经尝试将类方法更改为这样的咖喱方法:
editTema(index) {
return value => {
this.setState(prevState => {
const class = {...prevState.class};
class.topic = [...class.topic.slice(0, index), value, ...class.topic.slice(index +1)];
const newClass = {...prevState.class, class};
return {class: newClass};
})
}
}
然后我像这样传递了它:
editTopic ={(index) => this.editTopic(index)}
,然后在将处理程序传递给AutocompleteSelect
的子组件中:
handleChange={editTema(index)}
最后在AutocompleteSelect
中:
onChange={(event) => this.props.handleChange(event.target.value)}
但是,它仍然没有更改类组件的状态,我在控制台上没有看到该函数被称为。
应该是
editTopic={(index) => (value) => this.editTopic(index, value)}
然后
<AutocompleteSelect handleChange={editTopic(index)}/>
最后
onChange={(event) => this.props.handleChange(event.target.value)}
这不是一个好模式,因为对于不熟悉您的代码的人可能会注意到,他可能无法轻易弄清楚应该在某些层中提供哪个值。此外,将来您会发现切换到react-hooks
。
我建议通过参数。
editTopic={(index, value) => this.editTopic(index, value)}
然后
<AutocompleteSelect handleChange={editTopic} index={index}/>
最后
const { handleChange, index } = this.props;
...
onChange={(event) => this.props.handleChange(index, event.target.value)}
当您将 handler 从父零件到子组件传递时,您应该将参考传递给处理程序,而不是函数调用。
因此,在您的情况下,当通过editTopic()
时,您应该通过
<Component editTopic = {this.editTopic}></Component>