2017-04-16 51 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的反应。他们反作用,因为他们在很多情况下都做同样的事情 –