A
|-B
| |-C
| |-D
|
|-E
|-input
我有一个组件D,它位于组件树的一个单独的,更深的分支上作为组件E.当某个动作发生在D(或堆栈中的任何位置)时,我想将输入聚焦在E.我需要使用ref
以某种方式存储对输入的全局引用,或者是否有一些更好的方法来控制使用传奇的远程元素的文档焦点?
答案 0 :(得分:0)
这似乎有点不知道确切的细节,但这是我将如何实现它 -
1)“A”将“isEInputFocused”存储为状态
2)“A”具有切换上述状态值(开/关)的功能,并将此功能作为prop传递给任何其他想要触发“E”上的焦点/模糊的组件。 E.g。
state = {
isEFocused: false,
};
toggleEFocus() {
this.setState({ isEFocused: !this.state.isEFocused });
}
render() {
<div>
<D toggleEFocused={ ::this.toggleEFocus } />
<E isEFocused={ this.state.isEFocused } />
</div>
}
(双冒号是绑定函数,因此它可以正确访问“A”状态)
3)“E”然后从“A”接收它作为道具。同样在“E” componentWillReceiveProps 中,根据上述道具触发输入焦点。
componentWillReceiveProps(nextProps) {
if (nextProps.isEFocused) this._inputRef.focus();
else this._inputRef.blur();
// this._inputRef is the ref to the input in E
}
4)现在在“D”中,当某些动作发生时,只需触发从“A”向下传递的 toggleEFocus()