首页 > 解决方案 > 如何最小化 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 })
    }
}

标签: reactjs

解决方案


我们可以创建类型和字段名之间的映射,然后再次使用 JS 的计算属性特性。这种选择是松散的。

updateBugChange = (e, type)=>{
    const mapping = {
        title: 'bugTitle',
        type: 'bugType',
        description: 'bugDescription'
    }

    if(!mapping[type]) return;

    this.setState({
        [mapping[type]]: e.target.value
    })
}

推荐阅读