如何访问withStyle组件内部的DOM节点? [英] How I can access to DOM node inside of withStyle component?
问题描述
我正在进行 react
项目,在这个项目中,我和我的同事正在使用 Material UI
,出于某种原因,我想访问 DOM节点
由 HOC
包裹的另一个组件.我为此使用了 ref
.但我只是得到 withStyle
对象,见下文:
这是我的 TableHead
:
import从'react'导入React;从'prop-types'导入PropTypes;从'@ material-ui/core/styles'导入{withStyles};从'@ material-ui/core'导入{TableHead as MaterialTableHead,TableRow};从'./TableCell'导入TableCell;const TableHead =({类,头,... rest})=>(< MaterialTableHead {... rest}>< TableRow>{head.map(item =>(< TableCell键= {item.key} className = {classes.headCell} style = {{width:item.width}}>{item.title}</TableCell>))}</TableRow></MaterialTableHead>);TableHead.propTypes = {类别:PropTypes.object.isRequired,头:PropTypes.arrayOf(PropTypes.shape({密钥:PropTypes.string.isRequired,标题:PropTypes.string.isRequired,宽度:PropTypes.string,渲染:PropTypes.func,})).是必须的,};TableHead.defaultProps = {};const styles =()=>({headCell:{fontSize:'18px',颜色:#0c1d38",},});导出默认withStyles(styles,{withTheme:true})(TableHead);
在 Table
组件中,我想计算 TableHead
组件的高度,所以我使用以下代码:
< TableHead ref = {(header)=>{this.header =标头;}} head = {head}/>
以及 Table
组件的 componentDidMount
内部 console.log(this.header)
,如下所示:
我在网上寻找并找到一些 GitHub
问题页面,然后尝试使用 innerRef
而不是 ref
,但这对我没有帮助./p>
如何访问DOM节点以计算其高度?
您要查找的是 innerRef
属性.只需将 ref
替换为 innerRef
.
示例:
< TableHead innerRef = {(header)=>{this.header =标头;}} head = {head}/>
源( withStyles
文档):
一些实施细节可能会让您感兴趣的:
它添加了classes属性,因此您可以覆盖注入的类外面的名字.
它添加了一个innerRef 属性,以便您可以获取对包装组件的引用.innerRef的用法与ref相同.
它转发非React静态属性,因此此HOC更透明".例如,它可以用来定义一个getInitialProps()静态方法(next.js).
参考:enter image description here
I seek in the web and find some GitHub
issues pages and try innerRef
instead of ref
but it doesn't help me.
How I can access to DOM node to calculate its height?
What you are looking for is innerRef
property. Just replace ref
with innerRef
.
Example:
<TableHead innerRef={(header) => { this.header = header; }} head={head} />
Source (withStyles
docs):
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).
这篇关于如何访问withStyle组件内部的DOM节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!