javascript - 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
我做对了吗?还是有更好的方法?你能建议吗?
谢谢你。
解决方案
你tableRadius
在构造函数中调用。你只需要分配它。
class Dispatcher extends Component {
constructor(props) {
super(props);
this.tableRadius = tableRadius;
}
此外,与 一起React
,不喜欢使用DOM
api 直接操作元素。而是利用React
生态系统。在里面写下你的元素JSX
并在那里添加所需的侦听器。
推荐阅读
- r - lpp() 如何处理不完全落在段上的点?
- javascript - ٍ使用JSDOM时出错
- scala - 如何将未编译的 Spark Scala/spark-shell 代码作为 Dataproc 作业运行?
- azure-devops - 通过powershell安装部署组代理时出现服务器时间错误
- javascript - 如何复制文件夹中的文件进行构建?
- python - numpy.linalg.eig 返回的特征值何时排序?
- python - python - 如何迭代字符串/数组
- raspberry-pi3 - 无法更新 Raspbian
- c++ - Forward Declaration and Accessing member functions in an inherited class
- sleep - 智能手表访问