首页 > 解决方案 > Javascript 应用于不同的反应页面

问题描述

我需要在大部分反应页面中应用 javascript 代码。基本上是从帮助文件导出并在需要的所有页面上导入。以下代码在单个页面上运行良好,

tableRadius() {
    var tableHeader = document.getElementsByTagName('thead')[0].offsetHeight;
    var topValue = this.offsetTop - this.scrollTop;
    var top = Math.round(topValue + tableHeader);

    var verticalScroll = document.querySelector(".radius-wrapper");
    verticalScroll.setAttribute("style", "top:" + top + "px");
    return;
}

componentDidMount() {
    const table = document.getElementById("dispatchTable");
    table.addEventListener("scroll", this.tableRadius);
}

之后,我尝试将此代码添加到帮助文件中,以便我可以在不同的页面上使用它。我不知道我是否做对了,但我尝试在帮助文件中添加tablueRadius函数,但它有问题。这就是我的做法,

page.js

import { tableRadius } from '../../../services';

class Dispatcher extends Component {
  constructor(props) {
    super(props);
    this.tableRadius = tableRadius();
  }

  componentDidMount() {
    const table = document.getElementById("dispatchTable");
    table.addEventListener("scroll", this.tableRadius);
  }

}

帮助文件,服务

export function tableRadius() {
  var tableHeader = document.getElementsByTagName('thead')[0].offsetHeight;
  var topValue = this.offsetTop - this.scrollTop;
  var top = Math.round(topValue + tableHeader);

  var verticalScroll = document.querySelector(".radius-wrapper");
  verticalScroll.setAttribute("style", "top:" + top + "px");

  return;  
}

在这里,我在帮助文件上收到一个错误,上面写着,TypeError: Cannot read property 'offsetHeight' of undefined

我做对了吗?还是有更好的方法?你能建议吗?

谢谢你。

标签: javascriptreactjs

解决方案


tableRadius在构造函数中调用。你只需要分配它。

class Dispatcher extends Component {
  constructor(props) {
    super(props);
    this.tableRadius = tableRadius;
  }

此外,与 一起React,不喜欢使用DOMapi 直接操作元素。而是利用React生态系统。在里面写下你的元素JSX并在那里添加所需的侦听器。


推荐阅读