我的反应代码有一个问题。
我使用Material-ui和redux-form。我有类似的选择输入,更改此选择后,我应该在中重置值。我从react-form使用动作'change'并为文本字段设置值。但是标签仍然存在。我可以清除或重设值吗?
<Autocomplete
options={list}
getOptionLabel={option => option.name}
onInputChange={onChange}
onChange={onChangeAutoComplete}
noOptionsText='Нет доступных вариантов'
loadingText='Загрузка...'
openText='Открыть'
renderInput={params => (
<Field
{...params}
label={label}
name={fieldName}
variant="outlined"
fullWidth
component={renderTextField}
className={classes.textField}
margin="normal"
/>
)}
/>
答案 0 :(得分:23)
在value道具上使用钩子会破坏自动完成组件的功能(至少对我而言)。使用类和设置本地状态是相同的。
幸运的是,它是一个反应组件,因此具有“关键”道具。更改关键道具时,将使用默认值重新渲染组件(由于未选择任何内容,因此为空数组)。每当需要重置时,我都会在父组件中使用钩子并将这些值传递给键prop。
<Autocomplete key={somethingMeaningful} // Bool, or whatever just change it to re-render the component //...other props />
希望这会有所帮助!
答案 1 :(得分:4)
像这样在您的value
中使用<Autocomplete />
:
<Autocomplete
value={this.state.value} //insert your state key here
//...other props
/>
然后清除该键的状态,以清除自动完成字段值
答案 2 :(得分:3)
Material UI Autocomplete onInputChange
回调提供 reason
参数。如果输入已被输入更改,则原因将为 input
,如果您选择了选项,则原因将为 reset
。
onInputChange={(event, newInputValue, reason) => {
if (reason === 'reset') {
setValue('')
return
} else {
setValue(newInputValue)
}
}}
setValue
是 useState
,您可以将值状态传递给自动完成 value
属性。
答案 3 :(得分:1)
我通过在多个prop为false的情况下更新inputValue属性来实现此目的。如果使用多个道具,则存在一个问题(错误)。所选值不会被删除。
答案 4 :(得分:0)
为解决此问题,我创建了一个钩子来监视自动完成的value
状态,并在checkClear
返回true
时设置输入值;
function useAutocompleteInputClear(watch, checkClear) {
const elmRef = useRef(null);
useMemo(() => {
if (!elmRef || !elmRef.current) return;
if (!checkClear || typeof checkClear !== "function") return;
const button = elmRef.current.querySelector("button")
if (checkClear(watch) && button) {
button.click();
}
}, [watch])
return elmRef;
}
它的第一个参数是应注意的值,第二个参数是返回布尔值的函数。如果是true
,将进行清除。
同样,该钩子返回一个ref
,需要将其作为引用传递给Autocomplete
。
const elmRef = useAutocompleteInputClear(value, v => !v || !v.id)
<Autocomplete ref={elmRef}
value={value}
...
答案 5 :(得分:-1)
我将发布一种清除自动完成值的非常脏的方法。仅当其他方法无效时才尝试;
import React, { useRef } from 'react';
...
const autoC = useRef(null);
...
<Autocomplete
...
ref={autoC}
/>
然后当您要清除该值时;
const ele = autoC.current.getElementsByClassName('MuiAutocomplete-clearIndicator')[0];
if (ele) ele.click();