首页 > 解决方案 > 在不使用 refs 的情况下处理所有输入字段的更改事件

问题描述

我已经读过使用 refs 在反应中是反模式的。所以我使用下面的函数来获取输入的值。我的子组件中有三个输入字段:名称、用户名和密码。

为了获得他们的价值,我这样做:

 handleChange = (e) => {
      this.setState({
        inputVal: e.target.value
      })
    }

但是我不想为所有三个字段编写三次相同的函数,那么如何为一个函数handleChange中更改的特定输入字段执行此操作?

标签: reactjs

解决方案


Pull the state up to the parent component where these input fields will be called and pass the handleChange function to each of the input element as a prop.

<input type=“text” ... onChange={handleChange} />

Add all your logic for how the values should be saved in the state using your handleChange function.

This way, regardless of which element change you want handled, all you have to do is pass the handleChange function as a prop and set the value in the state as (say) an object with keys as field name which can be retrieved from the event argument passed to the handleChange function


推荐阅读