【问题标题】:Not getting ref inside function in React在 React 中没有在函数内部获取 ref
【发布时间】:2019-03-31 19:23:12
【问题描述】:

以下是我的源代码,我在其中尝试获取组件的引用并检查单击是否发生在组件外部,但由于未定义而出现错误。让我知道我在这里做错了什么。

代码-

// @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>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs flowtype react-ref


    【解决方案1】:

    因为你想访问 this 这是你当前类的上下文。

    有几种方法可以解决这个问题。

    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>
        );
    

    【讨论】:

    • 它有效 :) 但我不需要在构造函数中定义它,为什么 handleClick 没有箭头功能?
    • @Nesh 您必须采用其中一种方法。有几种方法可以将函数绑定到类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2020-12-03
    • 2023-04-02
    • 2020-06-05
    相关资源
    最近更新 更多