我有一个非常烦人的问题,我需要有关我的组件的帮助。它在这样的上下文中使用:
<table>
<thead>/* ... */</thead>
<tbody>
<COMPONENT>
<ChildComponent>/* ... */</ChildComponent>
<ChildComponent>/* ... */</ChildComponent>
<ChildComponent>/* ... */</ChildComponent>
</COMPONENT>
</tbody>
</table>
子组件是一个包含其他组件但最终呈现简单 HTML 的组件<tr>
inside 组件.tsx,我需要获取第 n 个子节点的 DOM 值(offsetTop 和 clientHeight)。
我尝试过很多事情:
-
ReactDOM.findDOMNode(children[n])
给我:
参数似乎不是 ReactComponent。键:$$typeof、type、key、ref、props、_owner、_store
-
children[n].ref
只是给我空
- 无法向子项添加引用
- 这种作品:
children.map((child, index) =>
index === n ? (
<div style={{display: contents}} key={index} ref={ref}>
) : child
)
给我警告(但有效!):
index.js:2178 警告:validateDOMNesting(...): 不能作为 的子项出现。
在 tr (由 FoldControlContainer 创建)...
有更好的解决方案吗?我尝试使用 或其他“透明”的 DOM 组件而不是div
,但没有成功。
使用 React.cloneElement 为子元素设置引用:https://reactjs.org/docs/react-api.html#cloneelement https://reactjs.org/docs/react-api.html#cloneelement
ex:
React.cloneElement(child, {ref: this.setChildRef})}
export default class Test extends React.Component {
childrenRefs = {}
setChildRef = index => el => this.childrenRefs[index] = el;
showInfo = () => {
console.log('children', Object.keys(this.childrenRefs).map(key => this.childrenRefs[key].offsetTop))
}
render() {
return (
<div>
{ React.Children.toArray(this.props.children).map((c, index) => React.cloneElement(
c,
{ref: this.setChildRef(index)},
))}
<button onClick={this.showInfo} >test</button>
</div>
);
}
}
这是完整工作示例的链接:https://stackblitz.com/edit/react-cf33ge https://stackblitz.com/edit/react-cf33ge打开右下角的控制台可以看到输出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)