【问题标题】:ReactJS Element focus() not firingReactJS元素焦点()没有触发
【发布时间】:2018-02-01 14:14:02
【问题描述】:

我有一个数字输入字段,在收到来自条形码扫描仪的输入后,我正试图关注该字段。 实际上,扫描仪只是一个伪键盘,我观察 Tab 键是否被按下。

在 Edge 中,输入按预期获得焦点,但在所有其他经过测试的浏览器(Chrome/Firefox)中,输入没有获得焦点。自从我在 PC 上之后,Safari 一直没有睾丸。

// I'm using a lifecycle method to watch for a change to the components props. 
// The onInputFocused will unset the value, but I've disabled to this 
// to eliminate any possible race cases?!

componentDidUpdate() {
    if (this.props.detail.shouldFocus) {
        setTimeout(() => {
            this.qtyInput.focus();
        }, 250);
        //     this.props.onInputFocused(this.props.detail);
    }
}
render(){
    return (
        ...
        <input type="number" className="form-control" min="0" name="qty_received" value={detail.ReceiptQuantityReceived}
                        ref={(input) => { this.qtyInput = input }}
                        onChange={(e) => { onQtyReceivedChange(e, detail) }}
                        onBlur={() => { onReceiveShipmentRowBlur(detail) }} />
    );
}

我最初是在没有setTimeout 的情况下调用focus,但根据网上的一些建议尝试超时。我也尝试将输入更改为text,但这也没有任何效果。

this.qtyInput 执行console.log 会输出预期的元素。

我唯一能想到的另一件事是,用户扫描以通过类似功能获得焦点的模态,但在焦点调用应该发生时已被删除。

更奇怪的是,我在输入的 onBlue 事件中添加了一个 console.log,即使您无法在该字段中键入或有任何视觉焦点指示,它也会被触发。

【问题讨论】:

  • 我觉得你一定要试试 this.qtyInput.focus();在没有 setTimeout 的 componentDidMount() 中。
  • 在这种情况下,如果 this.props.detail.shouldFocus 为真,请尝试调试,因为到目前为止,您的关注点取决于此 prop 的值
  • 渲染时输入不应该有焦点(永远),因为当触发元素(扫描仪的输入字段)触发状态更改时元素将始终存在。该州正在按预期申请。 focus() 只是没有被触发。

标签: javascript reactjs


【解决方案1】:

您必须尝试的一件事是为您的 INPUT 元素添加此属性 (输入自动对焦..) 这个属性可以帮助你

【讨论】:

  • 这将在渲染元素时应用焦点。我需要根据另一个元素的输入以编程方式应用焦点。
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2015-08-22
  • 1970-01-01
  • 2016-06-23
  • 2018-12-05
  • 1970-01-01
相关资源
最近更新 更多