Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用React聚焦div元素_Javascript_Reactjs - Fatal编程技术网

Javascript 用React聚焦div元素

Javascript 用React聚焦div元素,javascript,reactjs,Javascript,Reactjs,是否可以使用focus()方法聚焦div(或任何其他元素) 我已将tabIndex设置为div元素: <div ref="dropdown" tabIndex="1"></div> 或者像这样: setActive(state) { ReactDOM.findDOMNode(this.refs.dropdown).focus(); } this.refs.dropdown.focus(); 但是当事件被触发时,组件不会获得焦点。我该怎么做?是否有其他(非输入)元

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

我已将tabIndex设置为div元素:

<div ref="dropdown" tabIndex="1"></div>
或者像这样:

setActive(state) {
  ReactDOM.findDOMNode(this.refs.dropdown).focus();
}
this.refs.dropdown.focus();
但是当事件被触发时,组件不会获得焦点。我该怎么做?是否有其他(非输入)元素可用于此

编辑:

嗯,看起来这实际上是可以做到的:

但它对我不起作用,这是我的全部代码:

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>
    );
  }
}
类颜色选择器扩展React.Component{
建造师(道具){
超级(道具);
此.state={
活动:错误,
值:“”
};
}
选择项目(颜色){
this.setState({value:color,active:false});
}
设置活动(状态){
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((颜色,索引)=>{
const colorClasses=classNames('colorpicker-item',[`colorpicker-item-${color}`]);
返回(
{this.selectItem(color)}}key={index}className=“colorpicker项目容器”>
);
});
返回(
{this.setActive(true)}}/>
this.setActive(false)}onFocus={()=>console.log('focus')}tabIndex=“1”ref=“dropdown”className={pickerClasses}>
{colorFields}
);
}
}
这就是问题所在:

this.setState({ active: state });
this.refs.component.focus();
Set state是重新渲染组件,调用是异步的,因此您正在聚焦,它只是在聚焦后立即重新渲染,而您失去了焦点。尝试使用
setState
回调

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

每次设置状态时,React都会重新绘制组件,这意味着组件会失去焦点。在这种情况下,如果希望基于prop或state元素聚焦元素,则可以方便地使用
componentdiddupdate
componentDidMount
方法

请记住,根据React Lifecycle文档,
componentDidMount
仅在第一次在屏幕上呈现组件后才会发生,并且在此调用中,
componentDidUpdate
不会发生,然后对于每个新的
setState
forceUpdate
调用或接收新道具的组件将执行
componentdiddupdate
调用

componentDidMount() {
  this.focusDiv();
},
componentDidUpdate() {
  if(this.state.active)
    this.focusDiv();
},
focusDiv() {
  ReactDOM.findDOMNode(this.refs.theDiv).focus();
}
这是一个你可以玩的游戏。

这在我的情况下很有效

render: function(){

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

    return <div ref={ divElement => this.divElement = divElement}
                contentEditable={props.edit}/>
}
render:function(){
if(this.props.edit){
setTimeout(()=>{this.divElement.focus()},0)
}
返回this.divElement=divElement}
contentEditable={props.edit}/>
}

不确定这是否是正确的方法,但我发现这对我很有效

render() {
  return <div ref='item' onLoad={() => this.refs.item.focus()}>I will have focus</div>
}
render(){
返回此.refs.item.focus()}>我将获得焦点
}

回答有点晚,但事件处理程序不工作的原因可能是因为您没有绑定函数,因此当您将其作为例如:“this.selectItem(color)”传递时,函数中使用的“this”将是未定义的

在构造函数中,请执行以下操作:

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

this.setActive = this.setActive.bind(this)
从“React”导入React
从“react dom”导入react dom;
导出默认类DivFocusReactJs扩展React.Component{
建造师(道具){
超级(道具)
此.state={
}
}
componentDidMount(){
ReactDOM.findDOMNode(this.refs.divFocus.focus();
}
render(){
返回(
用React聚焦div元素

{/*您的代码在这里…*/} ) }
}
您在哪里分配ref?抱歉,更新了,我正在使用tabIndexI将ref分配给同一个div元素。我尝试了这一点,但在我的代码中不起作用,我更新为问题,以包括它。这篇文章对我帮助很大:嗯,不,即使我没有调用setState,元素也没有获得焦点:(这很有趣,谢谢老兄!
componentdiddupdate
这个小把戏能在5年后更新JS小提琴吗(任何人)?这只是这个问题的最佳答案,如果有一个有效的示例,那就太好了。我自己也尝试过了,但我想我还不够熟练,谢谢你注意,我用一个箭头函数包装了setActive函数调用:
onFocus={()=>{this.setActive(true)}
,这样做可以为你提供正确的上下文,所以使用
.bind>(这)
不会改变代码段的工作方式。我可以知道上述解决方案会产生什么问题吗?当我尝试使用相同的代码时,它会按照问题工作。示例: