My onChange not working with react

廉价感情. 提交于 2020-01-17 07:00:43

问题


I have followed this documentation and have created a select tag with react.
I have edited this question, If I use className="browser-default" in select it works fine. But for materialize select it is not working.
onChange event is not working in my case. The function doesn't get called.

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>
        );
    }
}

I don't get any error here, but my degreeChange function doesn't get called. I am not getting what my error is.


回答1:


There is nothing wrong with your code. Are you sure its not working? Maybe you are assuming set state is synchronous when its not. Try logging the target.value. you can also print the state value in a callback to your 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 try changing the item around. you will see that state seems to be one behind. thats because the moment where you are printing it state hasn't finished its render cycle and the state has not updated.

Fiddle of my changes



来源:https://stackoverflow.com/questions/43434381/my-onchange-not-working-with-react

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