最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React material UI reset values - Stack Overflow

programmeradmin4浏览0评论

I'm using material UI with react.

I can't seem to be able to reset a form on submit without getting errors in the console.

If I have: <TextField defaultValue={myComment.title} refs="title" />

On Submit, if I do this: this.refs.title.setValue('') I get the following error in the console

Warning: setValue() method is deprecated. Use the defaultValue property instead. Or use the TextField as a controlled component with the value property.

So I tried to do: this.refs.title.defaultValue = '' but that didn't work.

I'm thinking I have to do a handleChange event? But seems very painful to set this up when all I want to do is clear the input field.

Thanks in advance for you help.

I'm using material UI with react.

I can't seem to be able to reset a form on submit without getting errors in the console.

If I have: <TextField defaultValue={myComment.title} refs="title" />

On Submit, if I do this: this.refs.title.setValue('') I get the following error in the console

Warning: setValue() method is deprecated. Use the defaultValue property instead. Or use the TextField as a controlled component with the value property.

So I tried to do: this.refs.title.defaultValue = '' but that didn't work.

I'm thinking I have to do a handleChange event? But seems very painful to set this up when all I want to do is clear the input field.

Thanks in advance for you help.

Share Improve this question edited Feb 2, 2020 at 8:07 Edric 26.8k13 gold badges87 silver badges95 bronze badges asked Feb 2, 2016 at 11:24 denislexicdenislexic 11.4k26 gold badges88 silver badges136 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

So, the best way to use this component that can help you to achieve easily what you need (even if its a bit verbose) would be passing an value and onChange properties to the TextField... You may handle the value on the state from your current component or even pass from parent's components as props..

A simple example:

handleInputChange(event) {
    this.setState({
        name: event.target.value
    })
}


cleanInput() {
    this.setState({
        name: ''
    })
}

<TextField value={this.state.name} onChange={this.handleInputChange.bind(this)} />

You can simply use getInputNode().value=""

So in you case it will be this.refs.title.getInputNode().value=""

Try this for resetting your TextField and Props and States:

reset = ()=> {
       var  m = "";
       document.getElementById('h1').value = m;
}

It will only reset your textField, and if you want to reset State or Props too then just add setState() method in it.

reset = ()=> {
           setState({
               firtName: '',
               lastName: ''
             })
 }

I just had this question and I see you can just write:

type="reset"

https://jsfiddle.net/hfcrsqy2/

发布评论

评论列表(0)

  1. 暂无评论