【问题标题】:Focusing div elements with React使用 React 聚焦 div 元素
【发布时间】:2017-01-03 15:12:12
【问题描述】:

是否可以使用focus() 方法聚焦 div(或任何其他元素)?

我已将 tabIndex 设置为 div 元素:

<div ref="dropdown" tabIndex="1"></div>

当我点击它时,我可以看到它得到了焦点,但是,我正在尝试像这样动态地聚焦元素:

setActive(state) {
  ReactDOM.findDOMNode(this.refs.dropdown).focus();
}

或者像这样:

this.refs.dropdown.focus();

但是当事件触发时组件没有获得焦点。我怎样才能做到这一点?我可以为此使用任何其他(非输入)元素吗?

编辑:

好吧,看来这实际上是可以做到的:https://jsfiddle.net/69z2wepo/54201/

但这对我不起作用,这是我的完整代码:

class ColorPicker extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      active: false,
      value: ""
    };
  }

  selectItem(color) {
    this.setState({ value: color, active: false });
  }

  setActive(state) {
    this.setState({ active: state });
    this.refs.dropdown.focus();
  }

  render() {
    const { colors, styles, inputName } = this.props;

    const pickerClasses = classNames('colorpicker-dropdown', { 'active': this.state.active });

    const colorFields = colors.map((color, index) => {
      const colorClasses = classNames('colorpicker-item', [`colorpicker-item-${color}`]);

      return (
        <div onClick={() => { this.selectItem(color) }} key={index} className="colorpicker-item-container">
          <div className={colorClasses}></div>
        </div>
      );
    });

    return (
      <div className="colorpicker">
        <input type="text" className={styles} name={inputName} ref="component" value={this.state.value} onFocus={() => { this.setActive(true) }} />
        <div onBlur={() => this.setActive(false) } onFocus={() => console.log('focus')} tabIndex="1" ref="dropdown" className={pickerClasses}>
          {colorFields}
        </div>
      </div>
    );
  }
}

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

React 每次设置状态时都会重绘组件,这意味着组件失去焦点。在这种情况下,如果您想基于道具或状态元素聚焦元素,使用componentDidUpdatecomponentDidMount 方法会很方便。

请记住,根据 React 生命周期文档,componentDidMount 只会在第一次在屏幕上渲染组件后发生,并且在此调用中componentDidUpdate 不会发生,然后对于每个新的setStateforceUpdate 调用或接收新道具的组件将发生componentDidUpdate 调用。

componentDidMount() {
  this.focusDiv();
},
componentDidUpdate() {
  if(this.state.active)
    this.focusDiv();
},
focusDiv() {
  ReactDOM.findDOMNode(this.refs.theDiv).focus();
}

这是一个JS fiddle,你可以玩弄。

【讨论】:

  • 这很有趣,谢谢! componentDidUpdate 成功了
  • 是否有可能在 5 年后更新 JS 小提琴(任何人)?这只是这个问题的最佳答案,如果有工作示例会很好。我自己也试过了,但我觉得我不够熟练,谢谢
【解决方案2】:

这就是问题所在:

this.setState({ active: state });
this.refs.component.focus();

设置状态正在重新渲染您的组件并且调用是异步的,因此您正在聚焦,它只是在聚焦后立即重新渲染而您失去焦点。尝试使用setState 回调

this.setState({ active: state }, () => {
   this.refs.component.focus();
});

【讨论】:

  • 嗯,不,即使我不调用 setState 元素也没有获得焦点:(
【解决方案3】:

回答有点晚了,但是您的事件处理程序不起作用的原因可能是因为您没有绑定您的函数,因此当您将函数内部使用的“this”传递为例如:“this.selectItem (颜色)”

在构造函数中做:

this.selectItem = this.selectItem.bind(this)

this.setActive = this.setActive.bind(this)

【讨论】:

  • 请注意,我用箭头函数包装了 setActive 函数调用:onFocus={() =&gt; { this.setActive(true) }},这样做会为您提供正确的上下文,因此使用 .bind(this) 不会改变 sn-p 的工作方式
【解决方案4】:

这在我的情况下有效

render: function(){

  if(this.props.edit){
    setTimeout(()=>{ this.divElement.focus() },0)
  }

    return <div ref={ divElement => this.divElement = divElement}
                contentEditable={props.edit}/>
}

【讨论】:

    【解决方案5】:

    不确定这是否正确,但我发现这对我有用。

    render() {
      return <div ref='item' onLoad={() => this.refs.item.focus()}>I will have focus</div>
    }
    

    【讨论】:

      【解决方案6】:

      import React from "react"
      import ReactDOM from 'react-dom';
      
      export default class DivFocusReactJs extends React.Component {
      
        constructor(props) {
          super(props)
          this.state = {
          }
        }
      
        componentDidMount() {
          ReactDOM.findDOMNode(this.refs.divFocus).focus();
        }
      
        render() {
          return (
            <div tabIndex={1} ref="divFocus">
              <p>Focusing div elements with React</p>
              {/*your code here...*/}
            </div>
          )
        }
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-19
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 2018-05-04
        • 1970-01-01
        • 2013-04-22
        • 2014-04-09
        相关资源
        最近更新 更多