如何以编程方式清除/重置react-select v2?

时间:2018-05-18 13:51:06

标签: reactjs react-select

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

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

这不会清除当前选择。

我在这里想念一下,还是没有完全实现?

18 个答案:

答案 0 :(得分:7)

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

例如:

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"));

Here's这是一个有效的例子。

答案 1 :(得分:2)

您可以使用参考清除反应选择的值。

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 link

答案 2 :(得分:2)

对于正在使用功能组件的用户,这是一个基本演示,其中介绍了如何重置基于某些更改/触发/ 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;

答案 3 :(得分:2)

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

class Example extends Component {

constructor() {
    super()
}

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

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

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

答案 4 :(得分:1)

以防万一,这是我的解决方案:我创建了一个按钮,通过将状态设置回初始值来清除所选值。

<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

答案 5 :(得分:1)

这是我的React-Select V3的工作实现,已通过Hooks通过编程方式清除。

您可以在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>
);

答案 6 :(得分:1)

我自己遇到了这个问题,并通过将key传递给React-Select组件并附加了所选值来解决了这个问题。然后,这会迫使ReactSelect在选择内容更新时重新呈现自己。

我希望这对某人有帮助。

import ReactSelect from 'react-select';

...

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

答案 7 :(得分:0)

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

<Select value={null} />

答案 8 :(得分:0)

如果有人使用Hooks寻找解决方案。 React-Select 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}
           /> 
}

答案 9 :(得分:0)

如果在React Developers面板中选中Select component,您将看到它被另一个状态管理器包装。因此,您基本上是指州经理,而不是选择本身。

enter image description here

幸运的是,StateManager具有状态)和一个值对象,您可以将其设置为所需的任何对象。

例如(这是从我的项目中获得的,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("Введите название")}
      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("Введите название")
    }

答案 10 :(得分:0)

您可以将值设置为空

   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>

答案 11 :(得分:0)

反应选择/创建。

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

'''
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;
'''

答案 12 :(得分:0)

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])

答案 13 :(得分:0)

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

答案 14 :(得分:0)

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>
    </>
  )
}

答案 15 :(得分:0)

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

答案 16 :(得分:-1)

我使用redux-observable。

初始状态:

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

我创建了一个用于填充首次选择的动作。更改第一次选择时,我叫一个动作来填充第二个。

成功填充后,首先将我设置为{secondSelectData[]secondSelectValuenull

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

答案 17 :(得分:-1)

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])