小编典典

在React JS中自动关注输入元素

reactjs

我无法自动聚焦在此组件中呈现的输入标签。我在这里想念什么?

class TaskBox extends Component {
  constructor() {
    super();
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.focus();
  }

  componentWillUpdate(){
    this.focus();
  }

  render() {
    let props = this.props;
    return (
      <div style={{display: props.visible ? 'block' : 'none'}}>
        <input
        ref={(input) => { this.textInput = input; }}
        onBlur={props.blurFN} />
        <div>
          <div>Imp.</div>
          <div>Urg.</div>
          <div>Role</div>
        </div>
        <div>
          <button>Add goal</button>
        </div>
      </div>
    )
  }
}

任何帮助表示赞赏。


阅读 279

收藏
2020-07-22

共1个答案

小编典典

有一个可用于自动聚焦的属性autoFocus,我们可以使用该属性来自动聚焦输入元素而不是使用ref

autoFocus与输入元素一起使用:

<input autoFocus />

我们也可以使用ref,但是使用ref时,我们需要在正确的位置调用focus方法,您在componentWillUpdate生命周期方法中调用该方法,该方法在初始渲染期间不会触发,而不是使用componentDidMountlifecycle方法:

componentDidMount(){
    this.focus();
}

shouldComponentUpdate
:始终在render方法之前调用,并且可以定义是否需要重新渲染或可以跳过。显然,在初始渲染时永远不会调用此方法。仅当组件中发生某些状态更改时,才会调用它。

shouldComponentUpdate 返回的true会立即调用
componentWillUpdate

componentDidMount
:一旦执行了render方法,就会调用componentDidMount函数。可以使用此方法访问DOM,从而可以定义DOM操作或数据获取操作。任何DOM交互都应始终在其中进行。

参考:https :
//facebook.github.io/react/docs/react-
component.html

2020-07-22