【发布时间】: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.log到componentDidMount和一个到getChildRef,看看哪个先登录。
标签: javascript reactjs create-react-app