【问题标题】:React-Bootstap-Typeahead: Manually set custom display value in onChange() upon menu selectionReact-Bootstrap-Typeahead:选择菜单时在 onChange() 中手动设置自定义显示值
【发布时间】:2021-10-17 00:53:54
【问题描述】:

在React-Bootstrap-Typeahead的onChange中,我需要手动设置一个自定义的显示值。我的第一个想法是使用ref 并执行类似于this example 中的.clear() 的操作。

但尽管.clear() 有效,inputNode.value = 'abc' 无效,我只剩下菜单中的旧选定值。

onChange={option => {
     typeaheadRef.current.blur(); // This works
     typeaheadRef.current.inputNode.value = 'abc'; // This does not work (old value is retained)
}}

我也尝试直接访问我知道其 ID 的 DOM 输入元素,然后做

var inputElement = document.querySelector('input[id=myTypeahead]');
inputElement.value = 'abc';

但这也没有用。在我更改value = 之后的一瞬间,我确实看到了新的显示标签,但很快它就消失了。我认为组件保存或保留了菜单选择的值。

注意:我不能使用selected,我使用defaultSelected。我已经介绍了一些与 Formik 相关的行为,但它不适用于 selected,所以我坚持使用 defaultSelected

【问题讨论】:

    标签: react-bootstrap-typeahead


    【解决方案1】:

    我发现的唯一解决方法是使用新的 defaultSelected="abc" 重新渲染 Typeahead 组件(隐藏和重新显示,从空白状态),这是控件的一次性安装时间值规范。

    我无法让 selected=.. 工作,我在组件周围有一个包装器,使它适合 Formik 自定义 onChangeonInputChangeselected 没有使用。

    因此,有效的简单解决方法是,如果 Typeahead 的可见性取决于某些条件(否则 不会 呈现),则使用它来暂时隐藏和重新显示组件( 全新的重绘),带有新的defaultSelected,例如

    /* Conditions controlling the visibility of the Typeahead */
    !isEmptyObject(values) &&
    (values.approverId === null || (values.approverId !== null && detailedApproverUserInfo) 
    )
    &&
        <AsyncTypehead defaultSelected={{...whatever is needed to build the string, or the literal string itself...}}
         ..
         
       // Given the above visibility condition, we'll hide/re-show the component
       // The below will first hide the control in React's renders
       setFieldValue("approver", someId);
       setDetailedUserInfo(null);
       // The below will re-show the control in React's renders, after a small delay (a fetch)
       setDetailedUserInfo(fetchDetailedUserInfo());
    

    【讨论】:

    • 从您的原始问题听起来好像您正在尝试设置自定义输入值,在这种情况下,defaultInputValue 可能比设置所选项目的defaultSelected 更合适.方法是相同的,因为不支持对输入值的外部控制。
    猜你喜欢
    • 2021-07-25
    • 2021-02-19
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多