reactjs - 如何最小化 React Condition 代码?
问题描述
我的应用程序中有三个文本框,所有三个文本框都具有相同的功能,例如当 onChange 函数发生时。我会将状态从空更改为文本框的当前目标值。我确实喜欢下面似乎是初级水平。你能帮我以反应的方式做吗?
updateBugChange = (e, type) => {
if(type === 'title')
{
this.setState({ bugTitle : e.target.value })
}
if(type === 'type')
{
this.setState({ bugType : e.target.value })
}
if(type === 'description')
{
this.setState({ bugDescription : e.target.value })
}
}
解决方案
我们可以创建类型和字段名之间的映射,然后再次使用 JS 的计算属性特性。这种选择是松散的。
updateBugChange = (e, type)=>{
const mapping = {
title: 'bugTitle',
type: 'bugType',
description: 'bugDescription'
}
if(!mapping[type]) return;
this.setState({
[mapping[type]]: e.target.value
})
}
推荐阅读
- jquery - 在gridview上应用jquery数据表和引导程序后,为什么它的列相距很远?
- node.js - 无法将 Stream 对象发送到 NodeJS 服务器
- git - 如何在 mergetool 期间选择整个 REMOTE 文件?
- excel - 使用 FSO 使用扩展通配符在记事本中打开 txt 文件
- laravel - 使用 Laravel 中的另一个关联字段为 dateRange 创建条件
- javascript - 覆盖本地存储
- ios - 我想要设计一堆用曲线连接的圆圈
- c# - 返回浮点数组时出现错误
- angular - Angular FlexLayout 自定义布局
- c# - 如何确保令牌来自登录的设备或浏览器