簡體   English   中英

反應輸入 onChange 不會觸發

[英]React input onChange won't fire

我目前有這個簡單的 React 應用程序,但我一生都無法觸發這些 onchange 事件。

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>

    );
  }
});

有趣的是,當我使用onChange={this.changeTitle (this)} ,事件會觸發,但changeTitle函數中的 ev 變量不是正確的。

嘗試:

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

或者:

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

代替:

onChange={this.changeTitle}

嘗試將 onChange 移動到父 div .. 這對我有用

接受的答案是正確的,但我想補充一點,如果您正在實施引導程序文檔中提供的單選組按鈕解決方案,請確保刪除周圍 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>

如果您保留如上代碼所示的數據切換選項,您自己添加到輸入字段的 onClick 和 onChange 事件將被忽略。

當你使用:

onChange={this.changeTitle (this)}

react 會自動調用提到的函數。 你需要像這樣調用函數:

onChange={this.changeTitle}

並將您提到的函數更改為箭頭函數,否則您不能在函數中使用“ this ”關鍵字。 在無箭頭函數中,“ this ”關鍵字不是您的函數的對象,因此您無法訪問您的變量。 如果需要將參數傳遞給函數,則應使用其他方法,例如bind()

const inputRef = useRef(null)

<input type="file" ref={inputRef} onChange={handleFileChange} onClick={()=>inputRef.current.value = null}/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM