2017-04-16 49 views
0

我跟着這個documentation並創建了一個帶有反應的選擇標籤。
我編輯了這個問題,如果我使用className =「瀏覽器默認」選擇它工作正常。但爲了實現,請選擇它不起作用。
onChange事件不適用於我的情況。該函數不會被調用。我的onChange不能與反應一起工作

import React from 'react'; 

class Upload extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state={ 
      degree:'' 
     } 
     this.upload=this.upload.bind(this); 
     this.degreeChange=this.degreeChange.bind(this); 
    } 
    componentDidMount() { 
     $('select').material_select(); 
    } 
    degreeChange(event){ 
     this.setState({degree:event.target.value}); 
     console.log(this.state.degree); 
    } 
    upload(){ 
     alert(this.state.degree); 
    } 
    render() { 
     return (
      <div className="container"> 
      <form onSubmit={this.upload}> 
       <div className="input-field col s4"> 
         <select value={this.state.degree} onChange={this.degreeChange}> 
          <option value="" disabled>Choose Degree</option> 
          <option value="B.E">B.E</option> 
          <option value="B.Tech">B.Tech</option> 
         </select> 
       </div> 
       <div className="row center-align"> 
        <input className="waves-effect waves-light btn centre-align" type="submit" value="Submit"/> 
       </div> 
      </form> 
     </div> 
     ); 
    } 
} 

我在這裏沒有得到任何錯誤,但我的degreeChange函數沒有被調用。我沒有得到我的錯誤。

+0

[使用陣營JS爲下拉OnChange事件]的可能的複製(http://stackoverflow.com/questions/28868071/onchange-event-using-react-js-for-drop-down) –

+0

@JohnRuddell,我認爲這個問題不是你粘貼的鏈接的重複,這與** setState **的異步性質有關,這沒有任何'onChange'問題。 –

+0

[如何從選定的下拉列表中獲取最新值]可能的重複(http://stackoverflow.com/questions/39506293/how-to-get-the-latest-value-from-selected-drop-down) –

回答

0

你的代碼沒有問題。你確定它不工作?也許你假設設置狀態是不同步的。嘗試記錄target.value。您也可以將回調中的狀態值打印到setstate中。

degreeChange(event){ 
    console.log(`event value is ${event.target.value}`); 
    this.setState({degree:event.target.value},() => { 
     console.log(this.state.degree); 
    }); 
} 

Fiddle of your exact code請嘗試更改周圍的項目。你會看到那個國家似乎落後了。那是因爲你打印它的狀態的時刻還沒有完成它的渲染週期,並且狀態沒有更新。

Fiddle of my changes

+0

我看到它在小提琴中工作。但它不適用於我的情況。甚至在setState之前的console.log不起作用。看起來像degreeChange函數本身沒有被調用。 –

+0

我正在使用select從'http:// materializecss.com/forms.html'我有我的'$('select')。material_select();'在componentDidMount()方法中。如果我讓它默認選擇,那麼它工作正常。 –

+0

你不應該使用jQuery的反應。他們反作用,因爲他們在很多情況下都做同樣的事情 –