小编典典

用React聚焦div元素

reactjs

是否可以使用该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>
    );
  }
}

阅读 310

收藏
2020-07-22

共1个答案

小编典典

每当您设置状态时,React都会重绘组件,这意味着组件会失去焦点。在这种情况下,如果要基于prop或state元素集中元素,则可以使用componentDidUpdateor
componentDidMount方法。

请记住,按照阵营生命周期的文档,componentDidMount将只呈现组件首次在屏幕上以后的事情了,而在此调用componentDidUpdate不会发生,那么对于每一个新的setStateforceUpdate电话或组件容纳新的道具componentDidUpdate会出现通话。

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

这是您可以使用的JS小提琴

2020-07-22