如何覆盖 ClearIndicator 的 onClick 以模糊控制在反应选择中清除?



我想在单击ClearIndicator按钮后立即模糊react-select中的控制字段。

我尝试使用自定义的ClearIndicator组件并为其定义onClick处理程序,但这似乎不会影响清除按钮的onClick行为。

有没有一种方法可以覆盖或修改ClearIndicator按钮的onClick行为,以便在单击Clear按钮时调用blur()方法?

下面给出了我尝试的代码。

// react-select main component
<Select
components={{ ClearIndicator }}
isSearchable
isClearable
/>
// custom clear button
export const ClearIndicator = (props: any) => {
const {
children = <>clear</>,
getStyles,
innerProps: { ref, ...restInnerProps },
} = props;
const handleClearValue = () => {
ref.blur();
};
return (
<div
{...restInnerProps}
ref={ref}
style={getStyles("clearIndicator", props)}
onClick={handleClearValue}
>
<div style={{ padding: "0px 5px" }}>{children}</div>
</div>
);
};

Codesandbox链接:https://codesandbox.io/s/solitary-voice-0qmvc?file=/example.jsx

我已经编辑了您的代码,并将对select本身执行的操作直接移动到默认组件中(select所在的位置(:

export default () => {

const selectRef = useRef(null);
const blurOut = () => {
selectRef.current.blur();
}
return (
<Select
ref={selectRef}
onChange={blurOut}
defaultValue={colourOptions[1]}
options={colourOptions}
components={ClearIndicator }
isClearable
/>
);
};

此外,从ClearIndicator元素中删除onClick

const ClearIndicator = (props) => {
const {
children = <CustomClearText />,
getStyles,
innerProps: { ref, ...restInnerProps }
} = props;

return (
<div
{...restInnerProps}
ref={ref}
style={getStyles("clearIndicator", props)}

>
<div style={{ padding: "0px 5px" }}>{children}</div>
</div>
);
};

提示:

决不使用useState来存储对元素的引用。使用useRef-点击此处查找更多

最新更新