Why can't I change my input value in React even with the onChange listener

不羁岁月 提交于 2019-12-03 04:29:59
César Landesa

Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:

<input
    className="form-control"
    type="text" value={this.state.name}
    id={'todoName' + this.props.id}
    onChange={e => this.onTodoChange(e.target.value)}
/>

and then in the function:

onTodoChange(value){
        this.setState({
             name: value
        });
    }

Also, you can set the initial state in the constructor of the Component:

  constructor (props) {
    this.state = {
        updatable: false,
        name: props.name,
        status: props.status
    };
  }

you can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top

<input type="text" onChange={e => this.setState({ text: e.target.value })}/>

I think it is best way for u.

you shoud add this " this.onTodoChange = this.onTodoChange.bind(this)'

and your function has event param(e) and get value

componentWillMount(){
        this.setState({
            updatable : false,
            name : this.props.name,
            status : this.props.status
        });
    this.onTodoChange = this.onTodoChange.bind(this)
    }


<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>

onTodoChange(e){
         const {name, value} = e.target;
        this.setState({[name]: value});

}

In react the component will re-render(or update) only if the state or the prop changes.

In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.

onTodoChange(event){
           // update the state
          this.setState({name: event.target.value});
    }

In react state will not change until you do it by using this.setState({}); That is why your console message showing old values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!