我的onChange无法正常工作 [英] My onChange not working with react

查看:71
本文介绍了我的onChange无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已遵循此文档并具有使用react创建了一个选择标签.
我已经编辑了这个问题,如果我在选择中使用className ="browser-default",它可以正常工作.但是对于实现选择,它不起作用.
在我的情况下,onChange事件不起作用.该函数不会被调用.

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

我在这里没有收到任何错误,但是我的degreeChange函数没有被调用.我没有得到我的错误是什么.

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

推荐答案

您的代码没有错.您确定它不起作用吗?也许您假设设置状态不是同步的,则它是同步的.尝试记录target.value.您还可以在回调状态中将状态值打印到setstate.

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.

我所做的更改

这篇关于我的onChange无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆