所以我试图使用这里解释的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} />
);
}
}
答案 0 :(得分:0)
我想问题是你没有将 getChildRef 挂载到上下文中。尝试将this.getChildRef = tihs.getChildRef.bind(this)
添加到父的构造函数。