如何处理在类组件中从父级传递到子级事件处理程序的附加参数

时间:2019-05-21 10:14:26

标签: javascript reactjs

我有一个父类组件,该组件应处理子组件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的情况下正确传递这样的道具?

更新

我尝试过将class方法更改为类似currying的方法:

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)}

但是,它仍然没有改变类组件的状态,我什至没有在控制台中看到该函数被调用。

2 个答案:

答案 0 :(得分:1)

应该是

Running the evict task with compensationTime 0ms

然后

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}/>

答案 1 :(得分:0)

当您将 Handler 从父组件传递到子组件时, 您应该将引用传递给处理程序,而不是传递函数调用。

因此,在您通过editTopic()的情况下,您应该只是通过

<Component editTopic = {this.editTopic}></Component>