在JS中自动聚焦输入元素

时间:2017-02-19 06:40:30

标签: javascript 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>
    )
  }
}

感谢任何帮助。

2 个答案:

答案 0 :(得分:16)

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

autoFocus与input元素一起使用:

<input autoFocus />

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

componentDidMount(){
    this.focus();
}

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

只要shouldComponentUpdate返回true,就会调用 componentWillUpdate

componentDidMount :一旦执行了render方法,就会调用componentDidMount函数。可以使用此方法访问DOM,从而可以定义DOM操作或数据提取操作。任何DOM交互都应该在这里发生。

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

答案 1 :(得分:-1)

为输入设置ID,然后在需要聚焦时使用.setAttribute('autoFocus', true)

相关问题