簡體   English   中英

無法在React中的函數內部獲取引用

[英]Not getting ref inside function in React

以下是我的源代碼,我試圖在其中獲取組件的引用,並檢查單擊是否發生在組件外部,但由於未定義而來,因此出現錯誤。 讓我知道我在這里做錯了。

代碼-

// @flow
import { PureComponent, createRef } from 'react';
import type { Props, State } from 'types';

class MyComponent extends PureComponent<Props, State> {
  static defaultProps = {
    myComponentBody: ''
  };

  state: State = {
    showMyComponent: false,
  };

  wrapperRef: { current: null | HTMLDivElement } = createRef();

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  handleClickOutside(e: SyntheticEvent<>) {
    console.log(`Inside --->`); // This function is triggering
    console.log(this); // I am getting #document whole html
    console.log(this.wrapperRef); // undefined
    console.log(wrapperRef); // Uncaught ReferenceError: wrapperRef is not defined
    if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
      this.setState({
        showMyComponent: false,
      });
    }
  }

  handleClick(e: SyntheticEvent<>) {
    this.setState({
      showMyComponent: true,
    });
  }

  render() {
    const { myComponentBody } = this.props;
    return (
      <div onClick={e => this.handleClick(e)} ref={this.wrapperRef}>
        {this.props.children}
        {this.state.showMyComponent && (
          <div>
            <div>{myComponentBody}</div>
          </div>
        )}
      </div>
    );
  }
}

由於您要訪問因此這是當前類的上下文。

有幾種解決方法。

1.在構造函數中綁定handleClickOutside

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

2.將handleClickOutside轉換為箭頭功能。

  handleClickOutside = (e: SyntheticEvent<>) => {
    console.log(`Inside --->`); // This function is triggering
    console.log(this); // I am getting #document whole html
    console.log(this.wrapperRef); // undefined
    console.log(wrapperRef); // Uncaught ReferenceError: wrapperRef is not defined
    if (this.wrapperRef && !this.wrapperRef.contains(e.target)) {
      this.setState({
        showMyComponent: false,
      });
    }
  }

3.或者您可以在點擊事件中綁定它

    return (
      <div onClick={this.handleClick.bind(this)} ref={this.wrapperRef}>
        {this.props.children}
        {this.state.showMyComponent && (
          <div>
            <div>{myComponentBody}</div>
          </div>
        )}
      </div>
    );

暫無
暫無

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

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