如何使用声明/功能样式库(如Redux和ReactJS)来处理焦点?

jpi*_*son 10 focus flux reactjs redux

在查看其他开发人员在使用Redux时处理输入焦点的方式时,我遇到了一些针对ReactJS组件的一般指导.然而,我担心的是focus()函数是必不可少的,我可以看到多个组件争夺焦点的奇怪行为.是否有一种处理焦点的redux方式?是否有人使用redux处理实用设置焦点并做出反应,如果有,你使用什么技术?

有关:

ela*_*ado 8

我的方法是使用ref回调,这是一种onRenderComplete元素.在该回调中,我可以关注(有条件地,如果需要)并获得未来聚焦的参考.

如果在操作运行后有条件地呈现输入,则该ref回调应该触发焦点,因为在调用操作之后ref仍然不存在,但仅在完成渲染之后.处理像是一团糟的componentDidUpdate事情focus.

// Composer.jsx -- contains an input that will need to be focused somewhere else

class Composer extends Component {
  render() {
    return <input type="text" ref="input" />
  }

  // exposed as a public method
  focus() {
    this.refs.input.focus()
  }
}

// App.jsx

@connect(
  state => ({ isComposing: state.isComposing }),
  ...
)
class App extends Component {
  render() {
    const { isComposing } = this.props // or props, doesn't matter
    return (
      <div>
        <button onClick={::this._onCompose}>Compose</button>
        {isComposing ? <Composer ref={c => {
          this._composer = c
          this._composer && this._composer.focus() // issue initial focus
        }} /> : null}
      </div>
    )
  }

  _onCompose() {
    this.props.startComposing() // fire an action that changes state.isComposing

    // the first time the action dispatches, this._composer is still null, so the ref takes care of the focus. After the render, the ref remains so it can be accessed:

    this._composer && this._composer.focus() // focus if ref already exists
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么不autoFocusisFocued道具?

作为HTMLInputElement具有value作为一个道具,而是focus()作为一种方法-而不是isFocused道具-我会继续使用的方法来处理这个问题. isFocused可以得到一个值,但如果用户模糊输入,该值会发生什么变化?它会不同步.此外,如评论中所述,autoFocus可能与多个组件冲突

那么如何决定道具和方法呢?

对于大多数情况,道具将是答案.方法只能用于"即发即忘"的事情,例如scrollToBottom在新消息进入时的聊天scrollIntoView等.这些是商店不关心的一次性行为,用户可以通过交互进行更改,因此布尔道具不适合.对于所有其他事情,我会选择道具.

这是一个jsbin:

http://jsbin.com/waholo/edit?html,js,output