繁体   English   中英

如何以编程方式清除/重置 React-Select?

[英]How to programmatically clear/reset React-Select?

ReactSelect V2V3似乎有几个道具,如clearValueresetValuesetValue 无论我在尝试什么,我都无法以编程方式清除选择。 resetValue似乎无法从外部访问。

selectRef.setValue([], 'clear')
// or
selectRef.clearValue()

这不会清除当前选择。

我在这里错过了什么还是还没有完全实施?

如果您使用的是react-select ,您可以尝试将null传递给value prop。

例如:

import React from "react";
import { render } from "react-dom";
import Select from "react-select";

class App extends React.Component {
  constructor(props) {
    super(props);

    const options = [
      { value: "one", label: "One" },
      { value: "two", label: "Two" }
    ];

    this.state = {
      select: {
        value: options[0], // "One" as initial value for react-select
        options // all available options
      }
    };
  }

  setValue = value => {
    this.setState(prevState => ({
      select: {
        ...prevState.select,
        value
      }
    }));
  };

  handleChange = value => {
    this.setValue(value);
  };

  handleClick = () => {
    this.setValue(null); // here we reset value
  };

  render() {
    const { select } = this.state;

    return (
      <div>
        <p>
          <button type="button" onClick={this.handleClick}>
            Reset value
          </button>
        </p>
        <Select
          name="form-field-name"
          value={select.value}
          onChange={this.handleChange}
          options={select.options}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

这是一个工作示例。

我自己遇到了这个问题,并设法通过将一个key传递给 React-Select 组件来解决它,并将选定的值附加到它上面。 然后,这将强制ReactSelect在更新选择时重新呈现自身。

我希望这可以帮助别人。

import ReactSelect from 'react-select';

...

<ReactSelect
  key={`my_unique_select_key__${selected}`}
  value={selected || ''}
  ...
/>

您可以使用 ref 清除 react select 的值。

import React, { useRef } from "react";
import Select from "react-select";

export default function App() {
  const selectInputRef = useRef();

  const onClear = () => {
    selectInputRef.current.select.clearValue();
  };

  return (
    <div className="App">
      <h1>Select Gender</h1>
      <Select
        ref={selectInputRef}
        options={[
          { value: "male", label: "Male" },
          { value: "female", label: "Female" }
        ]}
      />
      <button onClick={onClear}>Clear Value</button>
    </div>
  );
}

这是 CodeSandbox 链接

只需将值存储在状态中,并使用 componentDidUpdate 等以编程方式更改状态...

class Example extends Component {

constructor() {
    super()
}

state = {
     value: {label: 'Default value', key : '001'}
}

render() {
   return(
      <Select
         ...
         value={this.state.value}
         ...
      />
   )
)}

注意: “值”应该是一个对象。

一个简单的选择是将null传递给value道具。

<Select value={null} />

这是我使用Hooks编程方式清除React-Select V3的工作实现。

您可以在CodeSandbox DEMO中使用它。 欢迎任何反馈。

const initialFormState = { mySelectKey: null };

const [myForm, setMyForm] = useState(initialFormState);

const updateForm = value => {
  setMyForm({ ...myForm, mySelectKey: value });
};

const resetForm = () => {
  setMyForm(initialFormState);
};

return (
  <div className="App">
    <form>

      <Select name = "mySelect"
           options = {options}
             value = {options.filter(({ value }) => value === myForm.mySelectKey)}
    getOptionLabel = {({ label }) => label}
    getOptionValue = {({ value }) => value}
          onChange = {({ value }) => updateForm(value)} />

      <p>MyForm: {JSON.stringify(myForm)}</p>

      <input type="button" value="Reset fields" onClick={resetForm} />

    </form>
  </div>
);

如果有人使用 Hooks 寻找解决方案。 反应选择 V3.05:

const initial_state = { my_field: "" }

const my_field_options = [
    { value: 1, label: "Daily" },
    { value: 2, label: "Weekly" },
    { value: 3, label: "Monthly" },
]

export default function Example(){
    const [values, setValues] = useState(initial_state);

    function handleSelectChange(newValue, actionMeta){
        setValues({
            ...values,
            [actionMeta.name]: newValue ? newValue.value : ""
        })
    }

    return <Select
               name={"my_field"}
               inputId={"my_field"}
               onChange={handleSelectChange}
               options={my_field_options}
               placeholder={values.my_field}
               isClearable={true}
           /> 
}

除了最重要的答案,请注意该值需要为“null”而不是“undefined”才能正确清除。

如果您在 React Developers 面板中选中 Select 组件,您将看到它被另一个 - 状态管理器包装。 因此,您的 ref 基本上是对 State manager 的参考,而不是对 Select 本身的参考。

在此处输入图像描述

幸运的是,StateManager 具有 state) 和一个值对象,您可以将其设置为您想要的任何值。

例如(这来自我的项目,resetGroup 是我附加到 DOM 中某个按钮的 onClick 处理程序):

<Select onChange={this.handleGroupSelect} 
      options={this.state.groupsName.map(group => 
                  ({ label: group, value: group }) )}
      instanceId="groupselect"
      className='group-select-container'
      classNamePrefix="select"
      placeholder={this.context.t("Enter name")}
      ref={c => (this.groupSelect = c)}
/>

    resetGroup = (e) => {
        e.preventDefault()
        this.setState({
            selectedGroupName: ""
        })
        this.groupSelect.state.value.value = ""
        this.groupSelect.state.value.label = this.context.t("Enter name")
    }

对于那些使用函数组件的人,这里有一个基本演示,说明如何根据一些更改/触发器/reduxValue 重置反应选择。

import React, { useState, useEffect } from 'react';
import Select from 'react-select';

const customReactSelect = ({ options }) => {
  const [selectedValue, setSelectedValue] = useState([]);


  /**
   * Based on Some conditions you can reset your value
   */
  useEffect(() => {
      setSelectedValue([])
  }, [someReduxStateVariable]);

  const handleChange = (selectedVal) => {
    setSelectedValue(selectedVal);
  };

  return (
    <Select value={selectedValue} onChange={handleChange} options={options} />
  );
};

export default customReactSelect;

反应选择/可创建。

该问题明确寻求反应选择/可创建的解决方案。 请找到以下代码,该问题的简单答案和解决方案。 您可以为您的特定任务修改代码。

import CreatableSelect from "react-select/creatable";

const TestAction = (props) => {
  const { buttonLabelView, className } = props;
  const selectInputRef = useRef();

  function clearSelected() {
    selectInputRef.current.select.select.clearValue();
  }

  const createOption = (label, dataId) => ({
    label,
    value: dataId,
  });

  const Options = ["C1", "C2", "C3", "C4"]?.map((post, id) => {
    return createOption(post, id);
  });

  return (
    <div>
      <CreatableSelect
        ref={selectInputRef}
        name="dataN"
        id="dataN"
        className="selctInputs"
        placeholder=" Select..."
        isMulti
        options={Options}
      />

      <button onClick={(e) => clearSelected()}> Clear </button>
    </div>
  );
};

export default TestAction;

在 v5 中,您实际上可以通过 prop isClearable={true}使其可清除,这很容易重置所选值

如果它对任何人有帮助,这是我的解决方案:我创建了一个按钮,通过将状态设置回其初始值来清除所选值。

<button onClick={() => this.clearFilters()} >Clear</button>

clearFilters(){
    this.setState({ startTime: null })
}

完整的代码示例如下:

 import React from "react" import Select from 'react-select'; const timeSlots = [ { value: '8:00', label: '8:00' }, { value: '9:00', label: '9:00' }, { value: '10:00', label: '10:00' }, ] class Filter extends React.Component { constructor(){ super(); this.state = { startTime: null, } } startTime = (selectedTime) => { this.setState({ startTime: selectedTime }); } clearFilters(){ this.setState({ startTime: null, }) } render(){ const { startTime } = this.state; return( <div> <button onClick={() => this.clearFilters()} >Clear</button> <Select value={startTime} onChange={this.startTime} options={timeSlots} placeholder='Start time' /> </div> ) } } export default Filter

您可以将值设置为 null

   const [selectedValue, setSelectedValue] = useState();
   const [valueList, setValueList] = useState([]); 
   const [loadingValueList, setLoadingValueList] = useState(true);


 useEffect(() => {
       //on page load update valueList and Loading as false
      setValueList(list);
      loadingValueList(false)
    }, []);

                                
  const onClear = () => {
     setSelectedValue(null);  // this will reset the selected value
  };

<Select
       className="basic-single"
       classNamePrefix="select"
       value={selectedValue}
       isLoading={loadingValueList}
       isClearable={true}
       isSearchable={true}
       name="selectValue"
       options={valueList}
       onChange={(selectedValue) => 
       setSelectedValue(selectedValue)}
      />
  <button onClick={onClear}>Clear Value</button>

在 react-select 的 value 属性中传递 null 将重置它。

if you are using formik then use below code to reset react-select value.

useEffect(()=>{
formik.setFieldValue("stateName", [])
},[])

Where stateName is html field name.

if you want to change value according to another dropdown/select (countryName) then pass that field value in useEffect array like below

useEffect(()=>{
formik.setFieldValue("stateName", [])
},[formik.values.countryName])

Zeeshan 的回答确实是正确的——你可以使用clearValue()但是当你这样做时, Select实例不会像你想象的那样重置为你的defaultValue道具。 clearValue()返回一个通用的Select...标签,在value中没有数据。

你可能想在你的重置中使用selectOption()来明确告诉react-select它应该重置为什么值/标签 我如何连接它(使用Next.jsstyled-componentsreact-select ):

import { useState, useRef } from 'react'
import styled from 'styled-components'
import Select from 'react-select'

// Basic button design for reset button
const UIButton = styled.button`
  background-color: #fff;
  border: none;
  border-radius: 0;
  color: inherit;
  cursor: pointer;
  font-weight: 700;
  min-width: 250px;
  padding: 17px 10px;
  text-transform: uppercase;
  transition: 0.2s ease-in-out;

  &:hover {
    background-color: lightgray;
  }
`

// Using style object `react-select` library indicates as best practice
const selectStyles = {
  control: (provided, state) => ({
    ...provided,
    borderRadius: 0,
    fontWeight: 700,
    margin: '0 20px 10px 0',
    padding: '10px',
    textTransform: 'uppercase',
    minWidth: '250px'
  })
}

export default function Sample() {
  // State for my data (assume `data` is valid)
  const [ currentData, setCurrentData ] = useState(data.initial)

  // Set refs for each select you have (one in this example)
  const regionOption = useRef(null)

  // Set region options, note how I have `data.initial` set here
  // This is so that when my select resets, the data will reset as well
  const regionSelectOptions = [
    { value: data.initial, label: 'Select a Region' },
    { value: data.regionOne, label: 'Region One' },    
  ]

  // Changes data by receiving event from select form
  // We read the event's value and modify currentData accordingly
  const handleSelectChange = (e) => {
    setCurrentData(e.value)
  }

  // Reset, notice how you have to pass the selected Option you want to reset
  // selectOption is smart enough to read the `value` key in regionSelectOptions 
  // All you have to do is pass in the array position that contains a value/label obj
  // In my case this would return us to `Select a Region...` label with `data.initial` value
  const resetData = () => {
    regionOption.current.select.selectOption(regionSelectOptions[0])
    setCurrentData(data.initial)
  }

  // notice how my `UIButton` for the reset is separate from my select menu
  return(
    <>
    <h2>Select a region</h2>
    <Select 
      aria-label="Region select menu"
      defaultValue={ regionSelectOptions[0] }
      onChange={ event => handleDataChange(event) }
      options={ regionSelectOptions }
      ref={ regionOption }
      styles={ selectStyles }
    />
    <UIButton 
      onClick={ resetData }
    >
      Reset
    </UIButton>
    </>
  )
}

下界的解决方案帮帮我。 这对我有用:

import React, { Component, Fragment } from "react";

import Select from "react-select";
import { colourOptions } from "./docs/data";

export default class SingleSelect extends Component {
  selectRef = null;

  clearValue = () => {
    this.selectRef.select.clearValue();
  };

  render() {
    return (
      <Fragment>
        <Select
          ref={ref => {
            this.selectRef = ref;
          }}
          className="basic-single"
          classNamePrefix="select"
          defaultValue={colourOptions[0]}
          name="color"
          options={colourOptions}
        />
        <button onClick={this.clearValue}>clear</button>
      </Fragment>
    );
  }
}

最重要的建议都没有对我有用,而且它们似乎都有些过头了。 这是对我有用的重要部分

<Select 
    value={this.state.selected && Object.keys(this.state.selected).length ? this.state.selected : null},
    onChange={this.handleSelectChange}
/>

StateManager 现在废除了,至少在 5.5.0 版本之后是这样。
现在如果你使用 ref,你可以这样做:

selectRef = null
<Select
  ...
  ref={c => (selectRef=c)}
/>
clearValue = () => {
   selectRef.clearValue();
};

这里的cSelect2 React 组件

这让我很烦,所以这里是:

React select 使用数组,所以你必须传递一个空数组而不是 null。

使用 React 的 useState:

import ReactSelect from 'react-select'

const Example = () => {

     const [val, setVal] = useState()

     const reset = () => {
         setVal([])
     }

     return <ReactSelect  
         value={val}/>
}

export default Example
//Create a function called onClear, and setSelected to empty string.

//Inside the handle submit function, call the onClear function. 

//This will work perfectly. 

//Example,

 const onClear = () => {
    setSelected("");
   
  };

const handleSubmit = ()=>{
  1 your data first ......(what you are posting or updating)
  2 onClear();
}
if you are using formik then use below code to reset react-select value.

useEffect(()=>{
formik.setFieldValue("stateName", [])
},[])

Where stateName is html field name.

if you want to change value according to another dropdown/select (countryName) then pass that field value in useEffect array like below

useEffect(()=>{
formik.setFieldValue("stateName", [])
},[formik.values.countryName])

我使用 redux-observable。

初始状态:

firstSelectData: [],
secondSelectData:[],
secondSelectValue: null

我创建了一个用于填充第一个选择的操作。 在更改第一个选择时,我会调用一个动作来填充第二个。

成功填充我设置的第一个选择( secondSelectData[]secondSelectValuenull

在第二次选择更改时我设置的第二次选择填充成功( secondSelectValuenull ),我调用了一个操作来使用所选的新值更新secondSelectValue

暂无
暂无

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

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