Javascript 我只是想重新设置它。如果我们花一天时间重置一个select控件。。我们应该什么时候提交它?太好了,注意到选择值应该是一个对象。一些超乎寻常的东西,但也不起作用。真的很好。如果您选择的值是object,请使用my\u unique\u select\u ke
Javascript 我只是想重新设置它。如果我们花一天时间重置一个select控件。。我们应该什么时候提交它?太好了,注意到选择值应该是一个对象。一些超乎寻常的东西,但也不起作用。真的很好。如果您选择的值是object,请使用my\u unique\u select\u ke,javascript,reactjs,react-hooks,react-select,Javascript,Reactjs,React Hooks,React Select,我只是想重新设置它。如果我们花一天时间重置一个select控件。。我们应该什么时候提交它?太好了,注意到选择值应该是一个对象。一些超乎寻常的东西,但也不起作用。真的很好。如果您选择的值是object,请使用my\u unique\u select\u key\uuu${JSON.stringify(selected)}。这可以工作,但请注意,它会使输入失去焦点。如果这很重要,你可以。只要value={selected | |''''}为我解决了这个问题。有人能在这里解释一下selected是什么
我只是想重新设置它。如果我们花一天时间重置一个select控件。。我们应该什么时候提交它?太好了,注意到选择值应该是一个对象。一些超乎寻常的东西,但也不起作用。真的很好。如果您选择的值是object,请使用
my\u unique\u select\u key\uuu${JSON.stringify(selected)}
。这可以工作,但请注意,它会使输入失去焦点。如果这很重要,你可以。只要value={selected | |''''}
为我解决了这个问题。有人能在这里解释一下selected
是什么吗?当您跟踪下拉列表的当前状态时,变量、关键字或字符串?选定的
将存储在某个状态中。当用户做出新的选择时,应更新此选项。这将导致关键点发生更改,并将重新渲染组件,因此将当前选定的值传递给它将确保它在正确选择的情况下执行此操作,您可以使用值Null。我尝试了使用react select浪费了我的时间。重置表单的简单性缺失,那么为什么要使用它呢?它变得非常复杂,本教程也是只有制作人才能理解的。如果选择此选项,您应该为值创建一个状态,该状态会在每次更改时设置,或者,您的字段将保持为空。它向我显示了一个错误:预期的类型来自属性“ref”,该属性在类型“IntrinsicatAttributes&IntrinsicClassAttributes&Readonly&Readonly”Hi@Zeeshan Ahmad上声明。您能告诉我如何使用refs清除值,而不将其添加回选项列表吗???如果import createableselect from'react select/createable'
,您需要使用createableselectref.current.select.select.clearValue()
谢谢!直截了当的解决方案。如果我们需要使用ref,那么它就是开发人员生命的终点。这不会使用react-select API来重置值。
selectRef.setValue([], 'clear')
// or
selectRef.clearValue()
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"));
<button onClick={() => this.clearFilters()} >Clear</button>
clearFilters(){
this.setState({ startTime: null })
}
<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")
}
import ReactSelect from 'react-select';
...
<ReactSelect
key={`my_unique_select_key__${selected}`}
value={selected || ''}
...
/>
class Example extends Component {
constructor() {
super()
}
state = {
value: {label: 'Default value', key : '001'}
}
render() {
return(
<Select
...
value={this.state.value}
...
/>
)
)}
<Select value={null} />
firstSelectData: [],
secondSelectData:[],
secondSelectValue: null
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}
/>
}
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;
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 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;
'''
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])
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])
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>
</>
)
}