React input onChange won't fire

眉间皱痕 提交于 2019-12-18 19:40:10

问题


I currently have this simple react app and I cannot get these onchange events to fire for the life of me.

var BlogForm = React.createClass({
getInitialState: function() {
    return {
        title: '',
        content: ''
    };
},
changeTitle: function(event) {

    var text = event.target.value;

    console.log(text);

    this.setState({
        title: event.target.value
    });
},
changeContent: function(event) {
    this.setState({
        content: event.target.value
     });
},
addBlog: function(ev) {
    console.log("hit hit");
},
render: function() {
    return (
                <form onSubmit={this.addBlog(this)}>
                    <div>
                        <label htmlFor='picure'>Picture</label>
                        <div><input type='file' id='picture' value={this.state.picture} /></div>
                    </div>
                    <div>
                        <input className="form-control" type='text' id='content' value={this.state.title} onChange={this.changeTitle} placeholder='Title' />
                    </div>
                    <div>
                        <input className="form-control" type='text' id='content' value={this.state.content} onChange={this.changeContent} placeholder='Content' />
                    </div>
                    <div>
                        <button className="btn btn-default">Add Blog</button>
                    </div>
                </form>

    );
  }
});

Funny thing is when I use onChange={this.changeTitle (this)}, the event fires but the ev variable in the changeTitle function is not the correct one.


回答1:


Try:

onChange={(evt) => this.changeTitle(evt)}

or:

onChange={this.changeTitle.bind(this)}

instead of:

onChange={this.changeTitle}



回答2:


try moving the onChange to the parent div.. this worked for me




回答3:


The accepted answer is correct, BUT I wanted to add that, if you are implementing the radio group button solution as provided in the bootstrap documentation, make sure to remove the "data-toggle" option on the surrounding div:

<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-secondary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Active
  </label>
</div>

If you keep the data-toggle option as shown in the code above, the onClick and onChange events you added yourself to the input field will be ignored.



来源:https://stackoverflow.com/questions/35115571/react-input-onchange-wont-fire

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