【发布时间】:2018-03-13 12:40:56
【问题描述】:
在阅读React set focus 和React focus with timeout 之后,我仍然有点困惑在输入上设置focus 的正确跨浏览器选项是什么。
我遇到了条件渲染输入的问题,在 table 中渲染后可能有焦点,其中 input 放置在 td 中。
1)componentDidUpdate解决方案:
//...
componentDidUpdate() {
this.input && this.input.focus();
}
render() {
const show = this.state.isShown;
return (
<td className="editable">
{!show ? (
<input
type="number"
ref={(input) => { this.input = input }}
value={this.state.value}
onBlur={this.save}
onKeyPress={e =>
e.which === 13 || e.keyCode === 13 ? this.save() : null}
/>
) : (
<span onClick={this.onTdClick}>{this.props.name}</span>
)}
</td>
);
}
此解决方案适用于 Chrome、IE11、Edge,但不适用于最新的 Firefox(点击span 后不出现输入事件。
2)requestAnimationFrame的解决方案:
//...
componentDidUpdate() {
if (!this.state.isShown) {
requestAnimationFrame(() => {
this.input && this.input.focus();
})
}
}
render() {
// same above
}
此解决方案适用于 Chrome、IE11、Edge,但 Firefox 在尝试设置 focus 时仍然不显示输入。
3)setTimeout(callback, n)的解决方案:
//...
componentDidUpdate() {
if (!this.state.isShown) {
setTimeout(() => {
this.input && this.input.focus()
}, 50);
}
}
render() {
// same above
}
这个案例适用于 Chrome、IE11、Edge 和(最后)Firefox,但似乎这是最“丑陋”的一个。
附: autoFocus attr 不适合这种情况,这里我有条件渲染,所以需要在click.之后设置焦点
所以,我的问题是:我们是否有正确的方法来解决此问题,无需为 Firefox 设置 setTimeout?
现场测试示例:codepen
【问题讨论】:
标签: javascript reactjs firefox focus