题意

在 React JS 中自动聚焦输入元素

问题背景:

I am unable to autofocus the input tag rendered in this component. What am I missing here?

我无法自动聚焦在这个组件渲染的输入标签上。我在这里漏掉了什么?

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

Any help is appreciated.

任何帮助都将不胜感激。

问题解决:

There is a attribute available for auto focusing autoFocus, we can use that for auto focusing of input element instead of using ref.

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

Using autoFocus with input element:

使用 autoFocus 与输入元素:<input autoFocus />

We can also use ref, but with ref we need to call focus method at correct place, you are calling that in componentWillUpdate lifecycle method, that method will not triggered during initial rendering, Instead of that use componentDidMount lifecycle method:

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

componentDidMount(){
    this.focus();
}

shouldComponentUpdate: is always called before the render method and enables to define if a re-rendering is needed or can be skipped. Obviously this method is never called on initial rendering. It will get called only when some state change happen in the component.

componentWillUpdate 总是在 render 方法之前被调用,并且可以用来判断是否需要重新渲染,或者可以跳过。显然,这个方法在初始渲染时不会被调用。只有当组件的某些状态发生变化时,它才会被调用。

componentWillUpdate gets called as soon as the the shouldComponentUpdate returned true.

componentWillUpdate 会在 shouldComponentUpdate 返回 true 时立即被调用。

componentDidMount: As soon as the render method has been executed the componentDidMount function is called. The DOM can be accessed in this method, enabling to define DOM manipulations or data fetching operations. Any DOM interactions should always happen in this.

一旦 render 方法执行完毕,componentDidMount 函数就会被调用。在这个方法中可以访问 DOM,从而可以进行 DOM 操作或数据获取。所有的 DOM 交互应始终在这个方法中进行。

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

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐