在React JS中自动关注输入元素 [英] AutoFocus an input element in react JS

查看:35
本文介绍了在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>
    )
  }
}

感谢您的帮助.

推荐答案

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

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 ,但是使用ref我们需要在正确的位置调用focus方法,您在 componentWillUpdate 生命周期方法中调用该方法,该方法将不会触发在初始渲染期间,请使用 componentDidMount 生命周期方法代替该方法:

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:

componentDidMount(){
    this.focus();
}

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

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 被调用一旦 shouldComponentUpdate 返回true.

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

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.

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

这篇关于在React JS中自动关注输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆