簡體   English   中英

ReactJS-ref返回“ undefined”

[英]ReactJS - ref returns “undefined”

我正在將ReactJS與NextJS一起使用。 當我嘗試設置ref ,控制台返回undefined ,這怎么可能? 如何解決這個困難? 我試圖在網絡上閱讀一些建議,但沒有成功。

這是我的摘錄:

 componentDidMount() { 
        this.myRef = React.createRef();
        window.addEventListener('scroll', this.handleScroll, { passive: true })
      }

      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll)
      }

      handleScroll(e) {
        e.preventDefault();
        // let offsetTop = this.myRef.current.offsetTop;

        // here I'm trying just a console.log to preview the value
        // otherwise my program will just crash
        console.log("I'm scrolling, offsetTop: ", this.myRef) 
      }

  render() {
    return (
        <div  className={style.solution_container_layout} >

            <div   ref={this.myRef} className={style.solution_item}>

任何提示都很好,謝謝

createRef返回的對象的current屬性是在第一個渲染上設置的,因此,如果在渲染componentDidMount之后在componentDidMount中創建它,則將不會設置它。

您也可以綁定handleScroll方法,或者this會不會是你所期望的。

 class App extends React.Component { myRef = React.createRef(); componentDidMount() { window.addEventListener("scroll", this.handleScroll, { passive: true }); } componentWillUnmount() { window.removeEventListener("scroll", this.handleScroll); } handleScroll = () => { console.log("I'm scrolling", this.myRef.current); }; render() { return <div ref={this.myRef} style={{ height: 1000 }}> Scroll me </div>; } } ReactDOM.render(<App />, document.getElementById("root")); 
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div> 

從添加的代碼很難看出來,但是您可能只是在構造函數中缺少此命令:

constructor( props ){
    super( props );
    this.handleScroll = this.handleScroll.bind(this)
}

更多信息: https : //medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM