【问题标题】:TypeError: Cannot read property 'refs' of undefined - Next.js App & ReactTypeError:无法读取未定义的属性'refs' - Next.js App & React
【发布时间】:2020-06-27 10:23:12
【问题描述】:

我的/pages/index.js

import { showFlyout, Flyout } from '../components/flyout'

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  showFo() {
    // Unhandled Runtime Error
    // TypeError: Cannot read property 'refs' of undefined
    // Source
    showFlyout(<Flyout title="My Flyout"><p>My <strong>FLYOUT</strong>!!!</p></Flyout>, this.refs.root)
    //                                                                                      ^
    console.log(this) // undefined
  }

  render() {
    return (
      <div ref="root">
        ...
        <button onClick={this.showFo}>Click me!</button>
      </div>
    )
  }
}

我的/components/flyout.js

import styles from './flyout.module.css' // No errors here
import ReactDOM from 'react-dom'

class Flyout extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            flyoutEleClassName: styles.flyout,
        };
    }

    ...

    render() {
        return (
            <div className={this.state.flyoutEleClassName} ref={(ref) => { this.flyoutEle = ref }}>
                ...
            </div>
        );
    }
}

function showFlyout(flyout, target) {
    ReactDOM.render(flyout, target) // This is the function I used in `/pages/index.js`
}

export { showFlyout, Flyout }

这是错误:

未处理的运行时错误 TypeError:无法读取未定义的属性'refs'

来源

showFlyout(<Flyout title="My Flyout"><p>My <strong>FLYOUT</strong>!!!</p></Flyout>, this.refs.root)
                                                                                        ^

【问题讨论】:

    标签: javascript reactjs next.js react-dom


    【解决方案1】:

    这里指的是this.flyoutEle:

    constructor(props) {
                super(props);
                this.flyoutEle = React.createRef();
    }
    
     <div className={this.state.flyoutEleClassName} ref={(ref) => { this.flyoutEle = ref }}>
                ...
            </div>
    

    那么您应该尝试使用 this.flyoutEle.current 而不是 this.refs.root

    让我知道这是否适合你!

    【讨论】:

    • 我的/pages/index.js 发生错误,而不是/components/flyout.js
    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-09-24
    • 2020-07-10
    • 2019-07-07
    • 2021-03-10
    相关资源
    最近更新 更多