【问题标题】:How to clear <Input type="select"> selected value in Reactstrap?如何清除 Reactstrap 中的 <Input type="select"> 选定值?
【发布时间】:2020-12-10 02:38:32
【问题描述】:

我在 Reactstrap 中有一个 &lt;select&gt; 对象,它是通过 Reactstrap 的 &lt;Input&gt; 组件创建的。我想以编程方式取消选择其中的选定对象,因此我使用状态来控制&lt;select&gt; 的值,并在我想清除状态时将状态设置为''(一个空字符串)。但是,这具有将选择对象中的第一项设置为被选择的效果,而不是取消选择它。

import React, { useState } from 'react';
import "./styles.css";
import {Input, Button} from 'reactstrap';

export default function App() {

  const [selectedOption, setSelectedOption] = useState<string>('');

  const onChangeSelection = (e: any) => {
    setSelectedOption(e.target.value);
  }

  const clearSelection = () => {
    setSelectedOption('');
  }

  return (
    <div className="App">
      <div>
        <Input type={"select"} size='2' value={selectedOption} onChange={onChangeSelection}>
          <option value={"option1"}>Option 1</option>
          <option value={"option2"}>Option 2</option>
        </Input>
      </div>
      <div>
        <Button onClick={clearSelection}>Clear selection</Button>
      </div>
    </div>
  );
}

有问题的例子

如何取消选择任何选定的项目?

【问题讨论】:

    标签: reactjs onclick html-input reactstrap react-functional-component


    【解决方案1】:

    添加值为空字符串的隐藏选项。

    import React, { useState } from "react";
    import "./styles.css";
    import { Input, Button } from "reactstrap";
    
    export default function App() {
      const [selectedOption, setSelectedOption] = useState<string>("");
    
      const onChangeSelection = (e: any) => {
        setSelectedOption(e.target.value);
      };
    
      const clearSelection = () => {
        setSelectedOption("hidden");
      };
    
      return (
        <div className="App">
          <div>
            <Input
              type={"select"}
              size="2"
              value={selectedOption}
              onChange={onChangeSelection}
            >
              <option value="" hidden></option>
              <option value={"option1"}>Option 1</option>
              <option value={"option2"}>Option 2</option>
            </Input>
          </div>
          <p>
            Clicking the clear button selects option 1, instead of deselecting any
            selected item.
          </p>
          <div>
            <Button onClick={clearSelection}>Clear selection</Button>
          </div>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2010-11-05
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 2014-12-10
      • 2014-12-26
      • 2015-08-11
      • 2018-06-28
      相关资源
      最近更新 更多