我正在尝试获取无状态子组件的高度,以便能够在父类中使用它的高度,但出现以下错误:Invariant Violation: Stateless function components cannot have refs.
简化代码
家长班
class App extends React.Component {
componentDidMount() {
console.log(this.header);
}
render() {
return (
<Child ref={component => this.header = component} />
)
}
}
孩子
const Child = () => (
<header ref="header">
Some text
</header>
)
有没有办法做到这一点?
这是带有错误的 Codepen的链接。
更新:
实际代码/上下文
所以我目前有一个 Header 组件,它看起来像这样:
export const Header = ({dateDetailsButton, title, logo, backButton, signUpButton, inboxButton, header}) => (
<header header className="flex flex-row tc pa3 bb b--light-gray relative min-h-35 max-h-35">
{signUpButton ? <Link to="/edit-profile-contact" href="#" className="flex z-2"><AddUser /></Link> : null }
{backButton ? <BackButton className="flex z-2" /> : null }
<h1 className={logo ? "w-100 tc dark-gray lh-solid f4 fw5 tk-reklame-script lh-solid ma0" : "w-100 tc dark-gray lh-solid f4 fw4 absolute left-0 right-0 top-0 bottom-0 maa h1-5 z-0"}>{title}</h1>
{dateDetailsButton ? <Link to="/date-details" className="absolute link dark-gray right-1 top-0 bottom-0 maa h1-5 z-2">Details</Link> : null }
{inboxButton ? <Link to="/inbox" href="#" className="flex mla z-2"><SpeechBubble /></Link> : null}
</header>
)
在某些情况下,我想向此 Header 添加逻辑以对其进行动画处理(例如,在用户滚动时的主页上,我正在为 Header 设置动画以在他们滚动经过某个点时变为固定 - 如果您愿意的话,这是一个粘性标题)。
我之前这样做的方法是只为具有特定功能(如上所述)和没有特定功能的标头创建一个单独的类。但是为了保持我的代码干燥,我已经将 Header 分离为它自己的功能性无状态组件,以便将其包装在 Class 中,从而为其提供粘性标题功能。
这是该类:
export default class FeedHeader extends React.Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
this.state = {
scrolledPastHeader: null,
from: 0,
to: 1,
}
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
this.setState({navHeight: this.navHeight.offsetHeight});
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(e) {
const { navHeight, scrolledPastHeader } = this.state;
const wy = document.body.scrollTop;
if (wy < navHeight) this.setState({scrolledPastHeader: null})
else if (wy > navHeight && wy < 100) {
this.setState({scrolledPastHeader: false})
}
else this.setState({scrolledPastHeader: true})
}
getMotionProps() {
const { scrolledPastHeader } = this.state;
return scrolledPastHeader === false ?
{
style: {
value: this.state.from
}
}
: {
style: {
value: spring(this.state.to)
}
}
}
render() {
const { brand, blurb } = this.props;
const { scrolledPastHeader } = this.state;
return (
<Motion {...this.getMotionProps()}>
{({value}) => {
return (
<Header ref="child" title={this.props.title} backButton={false} signUpButton inboxButton logo/>
);
}}
</Motion>
)
}
}
所以这就是这个特定问题的背景——我希望这能让事情更清楚一点。
Ps 抱歉缺少上下文,我想答案会比看起来更直接!