当 allowTextInput 为真时,如何防止 Office UI Fabric React DatePicker 弹出窗口窃取焦点?

How to prevent Office UI Fabric React DatePicker flyout from stealing focus when allowTextInput is true?

当使用 DatePicker from Office UI Fabric React

<DatePicker allowTextInput /> 

日期选择器弹出按钮占据了焦点,我需要再次单击日期选择器输入才能输入文本。

虽然这是记录在案的行为,但我想知道是否有办法阻止它发生。

两个可接受的替代方案是:

  1. 单击输入时未打开弹出窗口。
  2. 打开弹出按钮,但将焦点放在输入上

理想情况下,会有 autoOpenOnClick 标志或类似标志。

日历组件似乎有问题导致它窃取焦点(准确地说是上个月按钮(向上箭头)= 标注内的第一个可聚焦元素),即使有一个 calloutProp 应该允许您防止焦点改变(检查 _onCalloutPositioned 函数:https://github.com/OfficeDev/office-ui-fabric-react/blob/master/packages/office-ui-fabric-react/src/components/DatePicker/DatePicker.base.tsx#L303)。

试试这个,用一点时间来控制焦点:

dateRef = React.createRef();

...

<div ref={this.dateRef}>
    <DatePicker
        calloutProps={{setInitialFocus: false}} // This doesn't work
        label="Start date"
        allowTextInput={true}
        value={value}
        onFocus={this.onFocus}
        {...otherDatePickerProps}
    />
</div>

...

onFocus = () => {
    let node = ReactDOM.findDOMNode(this.dateRef && this.dateRef.current && this.dateRef.current.firstChild);
    node = node && node.querySelector && node.querySelector('.ms-TextField-fieldGroup');
    node = node && node.getElementsByTagName('input');
    node = node && node.length && node[0];
    setTimeout(function(){
      node.focus();
    }, 500);
}

基本上用 div 包装 DatePicker,您可以将引用 (dateRef) 保存到,然后找到输入元素并在稍等片刻后关注它(以确保您在日历完成窃取焦点后执行此操作)。如果需要,您可以 prune/clean 增加一些节点选择器逻辑。

如果还是没有解决问题,请尝试设置:

disableAutoFocus={true}

为您的日期选择器。

已在此提交(2019 年 10 月 23 日)中修复:
https://github.com/OfficeDev/office-ui-fabric-react/commit/fcbe8aca1e71114990a965a666b3c555113189d8