【问题标题】:React ref callback pattern returns undefined in Parent componentDidMount()React ref 回调模式在 Parent componentDidMount() 中返回未定义
【发布时间】:2017-09-18 20:56:03
【问题描述】:

所以我尝试使用此处解释的 ref 回调模式:https://facebook.github.io/react/docs/refs-and-the-dom.html,但在 Parent 的 componentDidMount 方法中继续未定义

const Child = ({ createFormHeight, getChildRef }) => (
  <CreateForm createFormHeight={createFormHeight}>
    // getting reference from here
    <div ref={getChildRef}>
      // form markup here
    </div>
  </CreateForm>
);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      createFormHeight: '',
    }
  }

  componentDidMount() {
    const createFormHeight = this.formWrapper.offsetHeight; // returns 
error that this.formWrapper is undefined
    this.setFormHeight(createFormHeight);
  }

  getChildRef = (el) => {
    // if I console.log(el) it returns the div here
    this.formWrapper = el;
  }

  setFormHeight = (height) => {
    this.setState(() => ({ createFormHeight: height }));
  };

  render() {
    const { createIsOpen, createFormHeight } = this.state;
    return (
      <CreateMember createFormHeight={createFormHeight} getChildRef=
{this.getChildRef} />
    );
  }
}

【问题讨论】:

  • 添加一个console.logcomponentDidMount和一个到getChildRef,看看哪个先登录。

标签: javascript reactjs create-react-app


【解决方案1】:

我想问题是您没有将 getChildRef 安装到上下文中。尝试将this.getChildRef = tihs.getChildRef.bind(this) 添加到Parent的构造函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2016-11-18
    • 2020-05-06
    • 2020-05-03
    • 2020-12-08
    相关资源
    最近更新 更多