简体   繁体   English

在 React.js 中单击按钮时重置/清除选择选项中的选定值?

[英]reset/clear selected values in select-option on button click in React.js?

I'm working on react and I have several drop-down and text fields where I want to clear/reset selected values from the select options and from the text field when I click the clear button.我正在研究 React,我有几个下拉和文本字段,当我单击清除按钮时,我想从选择选项和文本字段中清除/重置选定的值。 I've tried some logic, but it doesn't work.我试过一些逻辑,但它不起作用。 can someone help me?有人能帮我吗? I created a function called "handleReset" but it does nothing and doesn't show an error.我创建了一个名为“handleReset”的函数,但它什么也不做,也没有显示错误。

Here is my code:这是我的代码:

import React, { useState, useEffect } from "react";
import {
  Button,
  Container,
} from "react-bootstrap";
import { CarAction } from "../../Store/Actions/CarAction";
import { useDispatch, useSelector } from "react-redux";

const CarRequests = () => {
  const dispatch = useDispatch();
  const getCarMake = useSelector((state) => state.CarReducer.car);
  const getCarMileage = useSelector((state) => state.CarReducer.mileage);
  const getCarTrim = useSelector((state) => state.CarReducer.trim);

  let [value, setValue] = useState()

  let handleChange = (e) => {
    setValue(e.target.value)
  }

  const handleReset = (e) => {
    setValue(e.target.value = "");
  }

 
  useEffect(() => {
    dispatch(CarAction.CarMake());
    dispatch(CarAction.CarMileage());
    dispatch(CarAction.CarTrim());
  }, [dispatch]);

 
  return (
    <div className="flex-row align-items-center section">
      <h3>
        Filters
        <i className="fa fa-cog icon float-right"></i>
      </h3>
      <Container className="box-shadow p-4">
        <div className="form-row">
          <div className="form-group col-lg-3">
            <label>Make:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarMake.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}
            </select>

          </div>

          <div className="form-group col-md-3">
            <label>Model:</label>
            <select className="custom-select">
            <option value=''>Please select...</option>
              <option value="1">Option 1</option>
              <option value="2">Option 2</option>
              <option value="3">Option 3</option>

            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Year:</label>
            <select className="custom-select">
            <option value=''>Please select...</option>
              <option value="1">Option 1</option>
              <option value="2">Option 2</option>
              <option value="3">Option 3</option>
            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Mileage:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarMileage.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}

            </select>
          </div>

        </div>

        <div className="form-row">

          <div className="form-group col-md-3">
            <label>Car Trim:</label>
            <select className="custom-select" onChange={handleChange}>
            <option value=''>Please select...</option>
              {getCarTrim.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}

            </select>
          </div>

          <div className="form-group col-md-3">
            <label>Email:</label>
            <input type="email" placeholder="Email" className="custom-select" />
          </div>

          <div className="form-group col-md-3">
            <label>Phone no:</label>
            <input type="number" placeholder="Phone no" className="custom-select" />
          </div>

        </div>
        <div className="container-buttons">
          <Button className="mr-4" variant="light">
            Search
          </Button>

          <Button variant="dark" onClick={handleReset}>Clear</Button>
        </div>
      </Container>
    </div>
  );
};

export default CarRequests;

The thing you are doing wrong is in handleReset function you are taking the event and you are setting the target value to empty which is ideally wrong.您做错的事情是在 handleReset 函数中,您正在处理事件并将目标值设置为空,这在理想情况下是错误的。 In order to correct it we need to understand how the flow is working, you are using handleChange function in order to set the values to your state.为了纠正它,我们需要了解流程是如何工作的,您正在使用 handleChange 函数来将值设置为您的状态。 So in order to reset it you need to reset the value of the state only.所以为了重置它,你只需要重置状态的值。

So the code becomes like this:于是代码变成了这样:

const handleReset = () => {
    setValue("");   
}

Now this will reset the value of your state variable and also use your state variable in your select method which will resolve the problem.现在这将重置您的状态变量的值,并在您的选择方法中使用您的状态变量,这将解决问题。

<select value={value}>
<option></option>
.
.
</select>

To make dynamic field working:要使动态字段起作用:

 function App() { const [value, setValue] = useState({}); const arr = ["hello", "cra"]; const arr2 = [ { name: "hello", id: "1", }, { name: "test2", id: "2", }, ]; const handleChange = ({ target: { value: val, name } }) => { setValue({ ...value, [name]: val }); }; const resetValue = () => { setValue({}); }; console.log(value); return ( <div id="wrapper"> <select name="select1" value={value.select1 || ""} onChange={handleChange} > <option value=""></option> {arr.map((val) => { return <option value={val}>{val}</option>; })} </select> <select name="select2" value={value.select2 || ""} onChange={handleChange} > <option value=""></option> {arr2.map(({ name, id }) => { return <option value={id}>{name}</option>; })} </select> <button onClick={resetValue}>Reset</button> </div> ); }

Or else you can initialise the value in your state as well like this否则,您也可以像这样初始化状态中的值

const [value, setValue] = useState({select1: "" , select2: ""});

which could further be used dynamically in your select tag for name attributes.可以进一步在您的选择标签中动态使用名称属性。

 function App() { const [value, setValue] = useState({ select1: "", select2: "" }); const arr = ["hello", "cra"]; const arr2 = [ { name: "hello", id: "1", }, { name: "test2", id: "2", }, ]; const handleChange = ({ target: { value: val, name } }) => { setValue({ ...value, [name]: val }); }; const resetValue = () => { setValue({ select1: "", select2: "", }); }; console.log(value); return ( <div id="wrapper"> <select name="select1" value={value.select1} onChange={handleChange}> <option value=""></option> {arr.map((val) => { return <option value={val}>{val}</option>; })} </select> <select name="select2" value={value.select2} onChange={handleChange}> <option value=""></option> {arr2.map(({ name, id }) => { return <option value={id}>{name}</option>; })} </select> <button onClick={resetValue}>Reset</button> </div> ); }

Seems you are trying to store multiple values in the value .似乎您正在尝试在value存储多个值。 don't use the word value there.不要在那里使用 value 一词。 I have tried to change it to [formValue, setFormValue]我试图将其更改为[formValue, setFormValue]

Change 1:变化 1:

let [formValue, setFormValue] = useState({
textfield1: '',
dropdownfield2: ''});

Change 2 - for dropdown changed values:更改 2 - 对于下拉更改的值:

const handlDropDownChange = (event, value) => {
    setFormValue({
        ...formValue,
        ['dropdownfield2']: value,
    });
}

Change 3 - for mapping dropdown values from state, also use this to map to dropdown value:更改 3 - 用于从状态映射下拉值,也使用它来映射到下拉值:

formValue.dropdownfield2

Change 4 - for text field changes:更改 4 - 对于文本字段更改:

onChange={e => {
    updateFieldMyForm(e);
}}

const updateFieldMyForm= e => {
    setFormValue({
        ...formValue,
        [e.target.name]: e.target.value
    });
};

Note this will work for all text fields - just make sure that the name of this textfield matches the name used in the useState statement like - textfield1请注意,这适用于所有文本字段 - 只需确保此文本字段的名称与useState语句中使用的名称相匹配 - textfield1

Change 5 - to reset the whole thing at the end/submission更改 5 - 在结束/提交时重置整个内容

EDIT - 1编辑 - 1

const handleReset = () => { setFormValue({ textfield1: "", dropdownfield2: "" }); const handleReset = () => { setFormValue({ textfield1: "", dropdownfield2: "" }); }; };

Spread operator is the key in steps 2 & 4 [triple dots - ...] - let me know if you still have challenges.展开运算符是第 2 步和第 4 步 [三点 - ...] 中的关键 - 如果您仍有挑战,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM