react 自动查询
While I love ReactJS, I can say that I sometimes find interactions that were easy during the pre-ReactJS are annoyingly difficult or at least "indirect". One example is properly ensuring that a given <input>
element gets focused when a button in a different component is clicked; in the old days, it was three lines of code, but with React it can be more.
虽然我喜欢ReactJS,但我可以说有时候我发现在ReactJS之前很容易进行的交互非常麻烦,或者至少是“间接”的。 一个例子是正确地确保当单击不同组件中的按钮时,给定的<input>
元素会集中; 在过去,这是三行代码,但是使用React可以更多。
Let's have a look at a few strategies for properly focusing on <input>
elements with ReactJS.
让我们看一下使用ReactJS正确关注<input>
元素的一些策略。
autofocus
(autofocus
)
The autofocus
attribute is honored in ReactJS but only when the <input>
element is re-rendered with React:
在ReactJS中使用autofocus
属性,但仅当使用React重新渲染<input>
元素时:
<input type="text" autofocus="true" />
autofocus
is easy to use but only works when the <input>
is initially rendered; since React intelligently only re-renders elements that have changed, the autofocus
attribute isn't reliable in all cases.
autofocus
易于使用,但仅在最初呈现<input>
; 由于React只能智能地重新渲染已更改的元素,因此autofocus
属性在所有情况下都不可靠。
具有ref
componentDidUpdate
(componentDidUpdate
with ref
)
Since we can't rely solely on the autofocus
attribute, we can use componentDidUpdate
to complete the focus:
由于我们不能仅依赖于autofocus
属性,因此可以使用componentDidUpdate
来完成焦点:
class Expressions extends Component {
_input: ?HTMLInputElement;
// ....
componentDidUpdate(prevProps, prevState) {
this._input.focus();
}
render() {
return (
<div className={this.state.focused ? "focused": ""}>
<input
autofocus="true"
ref={c => (this._input = c)}
/>
</div>
);
}
}
}
componentDidUpdate
fires after the component is updated, so any change to the parent component would trigger this method and your <input>
would receive focus. In my cases, I usually toggle a className
on the parent element to signal the element is active and thus the componentDidUpdate
will trigger.
componentDidUpdate
更新后将触发componentDidUpdate,因此对父组件的任何更改都将触发此方法,并且您的<input>
将获得焦点。 就我而言,我通常在父元素上切换一个className
,以表明该元素处于活动状态,因此componentDidUpdate
将触发。
My perspective of inter-widget interaction has been formed by the days of Dojo's dijit UI framework where each widget usually had a reference to every child widget; with ReactJS the practice is (hopefully) avoiding ref
s and using state
, which is logical but there's still that piece of me that longs for a simple reference, which is why the second strategy makes sense to me.
我对小部件间交互的观点是在Dojo的dijit UI框架时代形成的,每个小部件通常都有对每个子小部件的引用。 使用ReactJS的做法是(希望)避免使用ref
并使用state
,这是合乎逻辑的,但是我当中仍然有人渴望获得简单的引用,这就是第二种策略对我有意义的原因。
react 自动查询