在父componentDidMount()中,React引用回调模式返回undefined

时间:2017-09-18 20:56:03

标签: javascript reactjs create-react-app

所以我试图使用这里解释的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} />
    );
  }
}

1 个答案:

答案 0 :(得分:0)

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