我是react原生的新手,我试图使用ES 6类将旧react的源代码重构到react中,但我得到了一个错误‘无法读取属性’关闭‘未定义的’。谁能告诉我为什么closeDrawer中的this.refs.drawer是未定义的?
closeDrawer = () => {
applicationActions.setDrawerStatus(false);
this.refs.drawer.close();
}
openDrawer = () => {
applicationActions.setDrawerStatus(true);
this.refs.drawer.open()
}
setDrawerState(value) {
this.setState({ isDrawerOpened: value });
}
render() {
return (
<Drawer ref="drawer"
type="static"
openDrawerOffset={DRAWER_OFFSET}
panOpenMask={.5}
onOpen={() => this.setDrawerState(true).bind(this)}
onClose={() => this.setDrawerState(false).bind(this)}
content={<DrawerScene closeDrawer={this.closeDrawer().bind(this)} />} >
<MainView
drawerStatus={this.isDrawerOpened}
closeDrawer={this.closeDrawer().bind(this)}
openDrawer={this.openDrawer().bind(this)}
/>
</Drawer>
);
}问候
发布于 2016-12-23 22:42:24
我没有注意到您在组件的成员函数中使用了箭头函数,所以您不需要编辑它们。不过,还有一些其他的问题。
这是一个具有约束力的问题。这应该是可行的:
closeDrawer = () => {
applicationActions.setDrawerStatus(false);
this.refs.drawer.close();
}
openDrawer = () => {
applicationActions.setDrawerStatus(true);
this.refs.drawer.open()
}
setDrawerState(value) {
this.setState({ isDrawerOpened: value });
}
render() {
return (
<Drawer ref="drawer"
type="static"
openDrawerOffset={DRAWER_OFFSET}
panOpenMask={.5}
onOpen={() => this.setDrawerState(true)}
onClose={() => this.setDrawerState(false)}
content={<DrawerScene closeDrawer={this.closeDrawer} />} >
<MainView
drawerStatus={this.isDrawerOpened}
closeDrawer={this.closeDrawer}
openDrawer={this.openDrawer}
/>
</Drawer>
);
}代码的问题在于,您正在将绑定应用于函数调用的结果。例如,当您执行this.setDrawerState(true).bind(this)时,将调用该函数,返回适当的值,然后对其应用bind。这通常会导致错误,但在这里,您还试图访问一个尚未设置的ref (因为在此之前,所有的prop值都必须在传递给新组件之前进行评估,这正是这里的问题所在,该函数是在组件实例化之前调用的)。
为了让您对bind有更多的了解:它是一个function对象的属性,所以您需要从对该函数(在本例中是它的名称)的引用中访问它。bind的结果是一个新函数,除了新的this值或您传递的任何其他参数之外,它的行为与原始函数相同。
发布于 2016-12-24 06:38:20
尝试像这样设置ref,而不是字符串:
drawer = null;
closeDrawer = () => {
applicationActions.setDrawerStatus(false);
this.drawer.close();
}
openDrawer = () => {
applicationActions.setDrawerStatus(true);
this.drawer.open()
}
setDrawerState(value) {
this.setState({ isDrawerOpened: value });
}
render() {
return (
<Drawer ref={((component)=> this.drawer=component)}
type="static"
openDrawerOffset={DRAWER_OFFSET}
panOpenMask={.5}
onOpen={() => this.setDrawerState(true).bind(this)}
onClose={() => this.setDrawerState(false).bind(this)}
content={<DrawerScene closeDrawer={this.closeDrawer().bind(this)} />} >
<MainView
drawerStatus={this.isDrawerOpened}
closeDrawer={this.closeDrawer().bind(this)}
openDrawer={this.openDrawer().bind(this)}
/>
</Drawer>
);
}https://stackoverflow.com/questions/41303339
复制相似问题