javascript - 如何对不同的输入使用相同的处理程序?

标签 javascript reactjs

我正在开发一个 React 项目,我的页面中有一些文本字段。我希望能够单独修改这些输入,同时仍然使用相同的处理程序。

当我尝试输入内容时,收到错误无法读取未定义的属性“相关”

这是我创建的函数:

handleChange(type) {
   console.log(type)                // outputs "one", "two', "three" when I reload the page
   return (event, type) => {
     console.log(event)                           // output the event when I type in the input
     console.log(event.target.value)              // output the value (the letter I typed)
     console.log(type)                            // output undefined
    this.setState(prevState => ({
      userInformation : {
        ...prevState.userInformation,
        [type] : {
          relevant: this.state.userInformation[type].relevant,
          other : event.target.value
          }
        }
      }))
    }
  }

输入:

<input type="text" value={this.state.userInformation.one.other}  onChange={this.handleChange('one')} className="probleme" />

<input type="text" value={this.state.userInformation.two.other}  onChange={this.handleChange('two')} className="probleme" />

<input type="text" value={this.state.userInformation.three.other}  onChange={this.handleChange('three')}  className="probleme" />

国家:

this.state = {
         userInformation: {
            one: {
              relevant: [ ],
             other: '',
            },
            two: {
              relevant: [ ],
              other: '',
            },
            three: {
              relevant: [ ],
              other: '',
            }
        },

有什么想法吗? 感谢您的宝贵时间!

最佳答案

像这样更新您的代码:

class MyAwesomeComponent {
  constructor(props){
     this.state = {
       one: '',
       two: '',
       three: ''
     }
  }

  handleChange = (evt)=> {
     const {name, value} = evt.target

     this.setState({...this.state, [name]: value})
  }

  render(){
     return(
         <React.Fragment>
             <input name="one" type="text" value={this.state.one}  onChange={this.handleChange} className="probleme" />

             <input name="two" type="text" value={this.state.two}  onChange={this.handleChange} className="probleme" />

             <input name="three" type="text" value={this.state.three}  onChange={this.handleChange}  className="probleme" />
         </React.Fragment>
     )
  }
}

关于javascript - 如何对不同的输入使用相同的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116542/

相关文章:

javascript - jQuery - 在 .load 调用完成之前禁用 HTML 页面

reactjs - 如何使 create-react-app 构建在 0.0.0.0 而不是 localhost 上监听?

javascript - 从范围输入( slider )获取值

javascript - 如何在递归 AJAX 调用中保留计数器?

javascript - angularJS:谷歌地图未加载地点API

javascript - Joomla 3 和自定义 jQuery 函数 - 未定义函数

html - 按钮内的图标不会触发 React 上的附加功能

reactjs - 如何使用react-router-redux的routeActions?

javascript - 如何在渲染前使用 setState 更新状态

javascript - useContext 给出错误无法读取未定义的属性 '...'