ReactSelect V2和V3似乎有几个道具,比如clearValue
,resetValue
和setValue
. 无论我在尝试什么,我都无法以编程方式清除选择。resetValue
似乎无法从外部访问。
selectRef.setValue([], 'clear')
// or
selectRef.clearValue()
这不会清除当前选择。
我在这里错过了什么还是它还没有完全实现?
ReactSelect V2和V3似乎有几个道具,比如clearValue
,resetValue
和setValue
. 无论我在尝试什么,我都无法以编程方式清除选择。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"));
这是一个工作示例。
我自己遇到了这个问题,并设法通过将 a 传递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}
...
/>
)
)}
注意:“值”应该是一个对象。
这是我使用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
给value
道具。
<Select value={null} />
如果您在 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;
除了最重要的答案,请注意该值需要为“null”而不是“undefined”才能正确清除。
该问题明确寻求反应选择/可创建的解决方案。请找到以下代码,该问题的简单答案和解决方案。您可以为您的特定任务修改代码。
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;
在 react-select 的 value 属性中传递 null 将重置它。
如果它对任何人有帮助,这是我的解决方案:我创建了一个按钮,通过将状态设置回其初始值来清除所选值。
<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>
下界的解决方案帮帮我。这对我有用:
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>
);
}
}
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])
在 v5 中,您实际上可以传递 propisClearable={true}
以使其可清除,从而轻松重置所选值
Zeeshan 的回答确实是正确的——你可以使用clearValue()
,但是当你这样做时,实例不会像你想象Select
的那样重置为你的道具。返回一个没有数据的通用标签。defaultValue
clearValue()
Select...
value
您可能想selectOption()
在您的重置中使用明确告诉 react-select
它应该重置为什么值/标签。我如何连接它(使用Next.js
,styled-components
和react-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>
</>
)
}
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
到[]
,secondSelectValue
到null
)
在第二次选择的填充成功中,我在第二次选择更改时设置(secondSelectValue
到null
),我调用一个动作来更新secondSelectValue
选择的新值