reactjs - 在不使用 refs 的情况下处理所有输入字段的更改事件
问题描述
我已经读过使用 refs 在反应中是反模式的。所以我使用下面的函数来获取输入的值。我的子组件中有三个输入字段:名称、用户名和密码。
为了获得他们的价值,我这样做:
handleChange = (e) => {
this.setState({
inputVal: e.target.value
})
}
但是我不想为所有三个字段编写三次相同的函数,那么如何为一个函数handleChange中更改的特定输入字段执行此操作?
解决方案
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
推荐阅读
- python - 为什么字典查找会导致“不可散列类型”错误,但使用直接值不会?
- java - Maven Deploy 插件创建 SYMLINK
- unity3d - 在哪里可以找到原始导出数据的 API 密钥
- reactjs - react-number-format:设置默认值
- javascript - 如何将 v-for 的值绑定到 v-if
- c# - 502 错误网关 nginx/1.16.1
- android - React Native - Android 动画 WebP 不工作
- c# - 如何在 asp.net core 中为 cookie 添加前缀?
- flutter - 登录不适用于 REST API
- amazon-web-services - AWS Amplify 上的 Gatsby 部署失败