首页 > 解决方案 > React-Bootstrap-Typeahead:在将选择设置为框之前捕获时刻(以允许有条件的拒绝)

问题描述

在 React-Boostrap-Typeahead 中,我需要在单击鼠标之后、菜单选择加载到 Typeahead 框之前捕获这一时刻。

这是因为我需要检查正在选择的项目,并且对于其中一些项目,我需要显示带有是/否警告的警报。只有单击是,我才能继续将该值设置到框中。否则我需要拒绝选择并保留它在鼠标单击之前的任何内容。

如果有任何解决方法,请告诉我。

标签: react-bootstrap-typeahead

解决方案


您应该能够在使用后实现您的目标onChange

const ref = useRef();
const [selected, setSelected] = useState([]);

return (
  <Typeahead
    id="example"
    onChange={(selections) => {
      if (!selections.length || window.confirm('Are you sure?')) {
        return setSelected(selections);
      }
      ref.current.clear();
    }}
    options={options}
    ref={ref}
    selected={selected}
  />
);

工作示例:https ://codesandbox.io/s/objective-colden-w7ko9


推荐阅读