gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:12:22 25 4
gpt4 key购买 nike

我正在做 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com