7

我正在尝试获取无状态子组件的高度,以便能够在父类中使用它的高度,但出现以下错误: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 抱歉缺少上下文,我想答案会比看起来更直接!

4

2 回答 2

8

好的,首先,感谢大家的回复-非常感谢!

我开始react-waypoints按照 Win 的建议实施,尽管很明显我需要更多地修改我的代码才能使其正常工作,所以我想我会进行最后一次搜索以尝试使用refs.

我正在寻找的答案实际上很简单,并且来自 mnpenner 的以下Github问题线程

解决方案

因为 React 不允许在无状态功能组件上使用 refs,所以您可以将功能组件包装在包装器中,同时为包装器提供自己的ref,如下所示:

  render() {
    return (
      <div ref={el => {this.childWrap = el;}}>
        <Child />
      </div>
    )
  }

然后,您可以通过定位包装器来访问组件的高度:

  componentDidMount() {
        if(this.childWrap && this.childWrap.firstChild) {
        let childHeight = this.childWrap.offsetHeight;
                console.log(childHeight);
    }
  }

虽然这可能不是最优雅的解决方案,但它确实暂时解决了我的问题。

这是一个 Codepen供参考。

于 2017-08-06T14:32:24.590 回答
1

这是使用 React-waypoint 的解决方案。你可以在这里查看: https ://codesandbox.io/s/qp3ly687

我为 onEnter 和 onLeave 添加了一个去抖动功能,这样它就不会像疯了一样更新状态,这样我们就可以在滚动时优化性能并且它不会锁定应用程序。同样,这是您可以做什么的一个非常粗略的想法,并且有很多选项可以改进实施。

=== 以前的

这是您可以通过保留无状态组件来解决此问题的一种方法。由于没有进一步解释上下文,这应该让您有机会了解如何获取位于无状态组件内的子组件的高度。

class App extends React.Component {
  componentDidMount() {
    console.log(this.child.offsetHeight);
  }
  render() {
    return (
      <div>
        <Wrapper>
          <div 
            ref={child => this.child = child}
            style={{height: 500}}>
            Some text!!
          </div>
         </Wrapper>
       </div>
    )
  }
}

const Wrapper = ({children}) => {
  return (
    <div>
      <header>Header</header>
      <div>{children}</div>
      <footer>Footer</footer>
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById("main")
);

于 2017-08-05T20:09:47.303 回答