reactjs - 从 componentDidMount 导出变量
问题描述
如何从 componentDidMount 导出“x”变量,以便在渲染部分使用它?我正在尝试检查我的 div 的 x 位置。
import React from 'react';
class Icon extends React.Component {
constructor(props) {
super(props);
this.selector = React.createRef();
}
componentDidMount = () => {
var rect = this.selector.current.getBoundingClientRect();
var x = rect.top;
console.log(x);
};
render() {
return (
<div className="icon" ref={this.selector}>
<p>x: {x} & y:</p>
</div>
);
}
}
export default Icon;
解决方案
Why not to use the state?
constructor(props) {
super(props);
state = {
x: null,
};
this.selector = React.createRef();
}
then inside lifecycle:
componentDidMount = () => {
var rect = this.selector.current.getBoundingClientRect();
this.setState({ x: rect.top });
};
and finally inside render:
<p>x: {this.state.x} & y:</p>
推荐阅读
- pandas - 用第一行值替换每个组中的行。Pandas Groupby
- python - 如何声明具有用户定义维度的 numpy 矩阵 np.zeros?
- r - 使用 eval(parse(text=...))) 将对象保存到 RData
- php - 更改 Apache 配置文件后的 Symfony 路由问题
- c# - Scriptable Object 实例的空引用异常,但它真的有效吗?
- python - 使用 docopt 和 unittest 测试 CLI
- java - 如何在 Spring Boot 中将 HttpServletRequest 标头转发到另一个 REST API
- r - R中分类树中的正类是什么意思?
- typescript - 多对多 TypeOrm NestJs 保存
- c# - 在 .Net 和 Node.js 之间传输大对象图