Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - React input onChange won't fire

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

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

or:

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

instead of:

onChange={this.changeTitle}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...