javascript - 如何访问 withStyle 组件内的 DOM 节点?

标签 javascript reactjs material-ui react-with-styles

我正在做 react 项目,在这个项目中,我和我的同事正在使用 Material UI,出于某种原因,我想访问 DOM 节点HOC 包装的另一个组件。为此,我使用了 React ref。但我只是得到了 withStyle 对象,见下文:

这是我的TableHead:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { TableHead as MaterialTableHead, TableRow } from '@material-ui/core';
import TableCell from './TableCell';

const TableHead = ({ classes, head, ...rest }) => (
  <MaterialTableHead {...rest}>
    <TableRow>
      {head.map(item => (
        <TableCell key={item.key} className={classes.headCell} style={{ width: item.width }}>
          {item.title}
        </TableCell>
      ))}
    </TableRow>
  </MaterialTableHead>
);

TableHead.propTypes = {
  classes: PropTypes.object.isRequired,
  head: PropTypes.arrayOf(PropTypes.shape({
    key: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    width: PropTypes.string,
    render: PropTypes.func,
  })).isRequired,
};

TableHead.defaultProps = {};

const styles = () => ({
  headCell: {
    fontSize: '18px',
    color: '#0c1d38',
  },
});

export default withStyles(styles, { withTheme: true })(TableHead);

Table 组件中我想计算 TableHead 组件的高度,所以我使用下面的代码:

<TableHead ref={(header) => { this.header = header; }} head={head} />

Table 组件的 componentDidMount 内部 console.log(this.header) 如下所示:

enter image description here

我在网上搜索并找到一些 GitHub 问题页面并尝试使用 innerRef 而不是 ref 但它对我没有帮助。

如何访问 DOM 节点以计算其高度?

最佳答案

您正在寻找的是 innerRef 属性。只需将 ref 替换为 innerRef

例子:

<TableHead innerRef={(header) => { this.header = header; }} head={head} />

来源(withStyles 文档):

Some implementation details that might be interesting to being aware of:

It adds a classes property so you can override the injected class names from the outside.

It adds an innerRef property so you can get a reference to the wrapped component. The usage of innerRef is identical to ref.

It forwards non React static properties so this HOC is more "transparent". For instance, it can be used to defined a getInitialProps() static method (next.js).

引用:https://material-ui.com/customization/css-in-js/#withstyles-styles---options----higher-order-component

关于javascript - 如何访问 withStyle 组件内的 DOM 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227495/

相关文章:

javascript - 在 Three.js 中旋转后沿世界轴平移

javascript - 指令内带有事件的动态 HTML 元素

reactjs - Uncaught ReferenceError : translate is not defined

reactjs - 删除Material-UI选择文本字段上的标签

javascript - 我需要使用 NodeJS 在页面内显示 OpenLayers 3 map 吗?

javascript - 找不到模块 'react-select/async' 的声明文件

javascript - 将 JavaScript 输入数字格式化为带两位小数的 float ,并强制执行所有操作

reactjs - 从自定义行组成 Material 表

reactjs - 如何在Elastic Search中存储用户执行的操作?

css - 如何更改文本字段中箭头的颜色从material-ui中选择