我怎样才能得到一个元素之后的高度呢?

HTML

<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>

ReactJS

var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return <div className="test">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);

RESULT

Size: 36px but it should be 18px after the render

它在渲染前计算容器高度(36px).我想得到渲染后的高度.在这种情况下,正确的结果应该是18px.jsfiddle

推荐答案

this小提琴(实际上更新了你的)

你需要钩住componentDidMount,它是在render方法之后运行的.在这里,你可以得到元素的实际高度.

var DivSize = React.createClass({
    getInitialState() {
    return { state: 0 };
  },

  componentDidMount() {
    const height = document.getElementById('container').clientHeight;
    this.setState({ height });
  },

  render: function() {
    return (
        <div className="test">
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    );
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
    <!-- This element's contents will be replaced with your component. -->
</div>

Reactjs相关问答推荐

全局上下文挂钩-替代不起作用

阻止在ShadCN和React中的FormLabel中添加 colored颜色

使用useReducer时,props 未从父级传递给子或孙级

useCallback()是否应该用于作为prop传递给子组件的函数,即使该组件包装在memo()中?

Next.js Next-Auth登录函数重定向到http://localhost:3000/api/auth/error

在迭代状态时无法读取未定义的属性(读取 map )

如何删除 bootstrap 手风琴上的边框

使用以Jest 的方式返回 Promise 的方法来模拟可构造的 API 类时出现问题

拖放 - 将排序保存到数组字段

如何在 TimePicker 中更改时钟 colored颜色 和确定按钮字体 colored颜色 - MUI React

当我使用 Firebase Auth 在 React 中刷新主页时显示登录页面

从 React 应用程序调用未经身份验证的 graphql 查询时出现错误:没有当前用户

为什么我会收到此错误:无法在我的react 包上读取 null 的属性(读取useState)?

react-router v6 中的 BrowserRouter 和 createBrowserRouter 有什么区别?我可以在不使用数据 API 的情况下使用 createBrowserRouter 吗?

如何在 React Native 中更新跨屏幕呈现的上下文状态变量?

null 不是对象(判断RNSound.IsAndroid)

在 React 中将路径与查询变量匹配

我正在try 使用 cypress 测试我的下拉列表,它 Select 值但不提交它们(手动工作)

如何从其他组件访问 useQuery refetch 方法?

根据计算 ReactJs 更新输入字段