提交后重置选择标签

时间:2019-02-16 14:51:05

标签: reactjs select

点击提交按钮后,我希望重置选择类型:

const types = ['text', 'color', 'date', 'email', 'tel', 'number'];

onSelect = ({ target }) => {
    const value = target.value;
    this.setState(curr => ({
      tempInput: { ...curr.tempInput, inputType: value }
    }));
};


<select onChange={this.onSelect} required>
    <option value=''>
        Please select a type
    </option>
    {types.map(type => (
        <option key={type} value={type}>
            {type}
        </option>
     ))}
</select>

表示单击该按钮时我将有一个“提交”按钮,我将重置状态,希望所选标签变回“请选择一种类型”,但是我不知道该怎么做, 希望能有所帮助, 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用其他状态变量来控制value中当前选择的select,并将其重置为''

示例

class App extends React.Component {
  state = {
    types: ["text", "color", "date", "email", "tel", "number"],
    selectedType: ""
  };

  onSelect = event => {
    this.setState({
      selectedType: event.target.value
    });
  };

  onReset = () => {
    this.setState({ selectedType: "" });
  };

  render() {
    const { types, selectedType } = this.state;

    return (
      <div>
        <select onChange={this.onSelect} required value={selectedType}>
          <option value="">Please select a type</option>
          {types.map(type => (
            <option key={type} value={type}>
              {type}
            </option>
          ))}
        </select>
        <button onClick={this.onReset}>Reset</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

您可以使用类似这样的内容:

 const types = ['text', 'color', 'date', 'email', 'tel', 'number'];



onSelect = ({ target }) => {
    const value = target.value;
    this.setState(curr => ({
      tempInput: { ...curr.tempInput, inputType: value }
    }));
};

onSubmit = () => {
    // Do some submit logic
    this.setState(curr => ({
        tempInput: { ...curr.tempInput, inputType: '' }
    })
}


<select onChange={this.onSelect} required>
    <option value='' selected={!this.state.tempInput.inputType}>
        Please select a type
    </option>
    {types.map(type => (
        <option key={type} value={type} selected={this.state.tempInput.inputType === type}>
            {type}
        </option>
    ))}
</select>