1
A
|-B
| |-C
|   |-D
|
|-E
  |-input

我有一个组件 D,它位于组件树的一个单独的、更深的分支上,作为组件 E。当某个动作发生在 D 中(或堆栈中的任何位置)时,我想将输入集中在 E 中。我需要以某种方式存储对输入的全局引用,ref或者是否有更好的方法来使用 sagas 控制跨远距离元素的文档焦点?

4

1 回答 1

0

在不知道确切细节的情况下,这似乎有点临时,但这是我将如何实现它 -

1)“A”将“isEInputFocused”存储为状态

2)“A”具有切换上述状态值(开/关)的功能,并将此功能作为道具传递给任何其他想要在“E”上触发焦点/模糊的组件。例如

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()

于 2016-05-04T23:57:02.457 回答