Reactjs 无法为无状态函数组件提供引用。但是我';我想把它交给一个类组件?
我有以下课程:Reactjs 无法为无状态函数组件提供引用。但是我';我想把它交给一个类组件?,reactjs,Reactjs,我有以下课程: class ModelList extends Component { constructor(props) { super(props); this.stickySidebar = React.createRef(); this.state = { bottomBorder: false }; } ... render() { const { title, button,
class ModelList extends Component {
constructor(props) {
super(props);
this.stickySidebar = React.createRef();
this.state = {
bottomBorder: false
};
}
...
render() {
const {
title,
button,
navHeight,
footerHeight,
children,
...props
} = this.props;
return (
<ModelListWrapper
{...props}
navHeight={navHeight}
footerHeight={footerHeight}
bottomBorder={this.state.bottomBorder}
>
<ModelListHeader>
{title && <H3>{title}</H3>}
{button && <Button {...button} color="link" size="sm" />}
</ModelListHeader>
<SidebarContainerSticky
id="sticky-sidebar-model-list"
ref={this.stickySidebar}
navHeight={navHeight}
footerHeight={footerHeight}
>
{children}
</SidebarContainerSticky>
</ModelListWrapper>
);
}
}
然而,我仍然得到同样的错误。除了将组件转换为基于类的组件之外,还有更高的障碍吗?或者我在这里遗漏了什么吗?现在应该可以了,您重新编译了代码吗?是的,但它仍然不起作用:/@OlivierBoissé还有其他想法吗?
clientHeight
只有在将ref
放在DOM节点上而不是React元素上时才起作用。也许您需要ReactDOM.findDOMNode(this.stickySidebar.current).clientHeight
,但不建议使用findDOMNode
,因此可能最好的解决方案是将ref转发到SidebarContainerSticky
的第一个DOM节点子节点哦,我的上帝,非常感谢你。我最终使用了React.forwardRef,稍后将添加响应。
class SidebarContainerSticky extends Component {
render() {
const { navHeight, footerHeight, ...props } = this.props;
return (
<div
{...props}
data-ut="sidebar-container-sticky"
style={{ height: `calc(100vh - ${navHeight + footerHeight}px)` }}
/>
);
}
}
export default withStyleClassName(
SidebarContainerSticky,
"sidebarContainerStickyClassName"
);