如何在React中重置选择下拉值

时间:2019-08-14 09:22:42

标签: javascript reactjs

我有一个html下拉选择控件,并且已将第一个选项值添加为Select。您还可以从下拉菜单中选择其他几个选项。现在,我想重置下拉列表的值并将其设置回Select

我如何在React中做到这一点?

这是我的代码

<select className="form-control" ref="Auditee" name="Auditee" onChange={this.handleChange.bind(this)}>
                <option>Select</option>
                {this.renderAuditee()}
              </select>
<button type="button" className="btn btn-primary" onClick={this.handleClear}>Clear</button>



renderAuditee(){
  let Auditeefiltered = this.state.review1data.map(element=> element.EEECPM).filter((value, index, self) => self.indexOf(value) === index)

  return Auditeefiltered.map(element=>
   <option>{element.toString().replace(/\[.*?\]/,'')}</option>
  )
}


handleClear(e){
 e.preventDefault();

    this.setState({
        filterData:[],
        filter: false
 });

我不知道如何重置选择下拉菜单。任何帮助都会有帮助

2 个答案:

答案 0 :(得分:1)

您的select应该是controlled

您需要具有用于所选值的状态变量。

state ={
   selected:''
}

受控选择应该是

<select className="form-control" value={this.state.selected} name="Auditee" onChange={this.handleChange.bind(this)}>
    <option>Select</option>
    {this.renderAuditee()}
</select>
handleChange = (e) => {
   this.setState({selected:e.target.value})
}

最后要清除选择,

handleClear = (e) => {
   this.setState({selected:""})
}

Demo

答案 1 :(得分:0)

上述答案的功能组件版本是

import logo from "./logo.svg";
import "./App.css";
import { useState } from "react";

function App() {
  const [data] = useState([1, 2, 3, 4]);
  const [selected, setSelected] = useState("");

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          React <code> SELECT RESET </code> demo.
        </p>
        <select value={selected} onChange={(e) => setSelected(e.target.value)}>
          <option>Select</option>
          {data &&
            data.map((d, index) => {
              return <option key={index}>{d}</option>;
            })}
        </select>
        <br />
        <button onClick={() => setSelected("")}>Clear</button>
      </header>
    </div>
  );
}

export default App;