首页 > 解决方案 > 如何定期自动对焦元素 - React

问题描述

我的 recat 应用程序需要帮助。我有一个按钮,一旦应用程序启动(自动对焦),它就会自行选择,这样您就可以通过键盘控制与其关联的功能。问题是,一旦我在页面上选择了另一个元素,按钮显然不再被选中,我无法再从键盘调用该功能。所以我想了解是否可以设置一个计时器,以便按钮每 x 秒选择一次。我附上组件代码。

import React, { Component } from "react";

class Spot extends Component {
  state = {
    index: 0,
    iframeSrcs: ["/300x250", "/160x600", "/468x60"],
    heightSrcs: [250, 600, 60],
    widthSrcs: [300, 160, 468],
    visibility: false
  };

  reload = () => {
    const iframeLength = this.state.iframeSrcs.length;
    if (this.state.index < iframeLength) {
      this.setState({
        index: this.state.index + 1,
        visibility: true
      });
    } else {
      this.setState({ index: 0, visibility: true }); //starting again
    }
    setTimeout(() => {
      this.setState({ visibility: false });
    }, 15000);
  };

  render() {
    return (
      <div>
        <button
          style={{
            position: "absolute",
            left: 0,
            right: 0,
            top: 500,
            opacity: 0
          }}
          onClick={this.reload}
          autoFocus="true"
          onKeyDown={this.reload}
        >
          pubblicità
        </button>
        {this.state.visibility ? (
          <iframe
            style={{
              position: "absolute",
              left: 100,
              right: 0,
              top: 10
            }}
            key={this.state.index}
            title="AdSlot"
            src={this.state.iframeSrcs[this.state.index]}
            height={this.state.heightSrcs[this.state.index]}
            width={this.state.widthSrcs[this.state.index]}
            scrolling="no"
            frameborder="0"
            allowFullScreen="true"
          />
        ) : (
          ""
        )}
      </div>
    );
  }
}
export default Slot;

感谢那些想帮助我的人。PS我知道我的代码的许多部分都不是最好的,但我现在正在接近反应,所以这是我能做到的最好的

标签: reactjs

解决方案


setInterval(() => {
    document.getElementById("your button id").focus();
}, your delay);

这不是特定的反应,而是香草 JS。我不知道它是否会起作用,但这是我现在能想到的最好的。你可以试一试,看看它是否有效。


推荐阅读