TypeError:无法读取未定义的React的属性“value”

时间:2018-05-25 19:18:46

标签: reactjs

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import UserInput from './learn/UserInput';


class App extends Component {


  state = {
    users : [
      {id:1, name:'manu', Age:28},
      {id:2,name:'john', Age:29},
      {id:3,name:'clint', Age:30},
    ]
  }


changeMethod = (event, id) => {

  const userIndex = this.state.users.findIndex( 
      (el) => {
      return  el.id === id;
      }

    ) 

  const user = {
    ...this.state.users[userIndex]
  };

  user.name = event.target.value;

  const users = [...this.state.users];

  users[userIndex] = user;

  this.setState({
    users : users
  })
}




  render() {

      let persons = (
           <div>

            {this.state.users.map( (el, index) => { 

              return (
                <div key ={el.id}>
                <p>{el.name}</p>

                <input type="text" name="" id="" onChange={this.changeMethod.bind(this, el.id)} 
                  value ={el.name}
                  />

                  </div>
              )
              })}

          </div> 
      )


    return (

        <div className="App">
            {persons}
        </div>

    );
  }
}

export default App;

这是我尝试输入输入框时出现的错误

TypeError: Cannot read property 'value' of undefined
App._this.changeMethod
src/App.js:33
  30 |   ...this.state.users[userIndex]
  31 | };
  32 | 
> 33 | user.name = event.target.value;
  34 | 
  35 | const users = [...this.state.users];

1 个答案:

答案 0 :(得分:2)

这是因为你绑定了onChange函数:

onChange={this.changeMethod.bind(this, el.id)}

因此在changeMethod方法中,第一个参数将始终为id,然后您将获得事件对象。

像这样写changeMethod

changeMethod = (id, event) => {
   ....
}
  

为什么会收到错误:“无法读取属性值   未定义“?

因为在你的情况下,事件(只是一个参数名称)将是一个值(你传递的id),并且event.target将是未定义的,这就是为什么“无法阅读...... ”

根据MDN Doc

  

function.bind(thisArg [,arg1 [,arg2 [,...]]])

     

arg1,arg2,... prepend 的参数提供给   调用目标函数时的绑定函数。

相关问题