[英]Passing props as ref and as method to child or sibling in React-Native
I am trying to make a AndroidDrawer using DrawerLayoutAndroid and ToolbarAndroid of react-native. 我试图使用react-native的DrawerLayoutAndroid和ToolbarAndroid制作一个AndroidDrawer。 When the hamburger icon on the toolbar is clicked, the drawer should open.
单击工具栏上的汉堡包图标时,应打开抽屉。
<DrawerLayoutAndroid ref={(element) => {
this.drawer=element;
}}
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<Toolbar toolbarText="XYZ" drawer={this.drawer}/>
</DrawerLayoutAndroid>
//Another file exported as Toolbar //另一个文件导出为工具栏
<ToolbarAndroid
navIcon={DrawerIcon}
onIconClicked={() => {
this.props.drawer.openDrawer();
}}
title={this.props.toolbarText}
style={[styles.toolbar,{backgroundColor:col}]}
/>
But when I press on the toolbar icon it says undefined is not a function for "_this2.props.drawer.openDrawer" . 但是,当我按工具栏图标时,它说undefined不是“ _this2.props.drawer.openDrawer”的函数 。
Alternatively when I make a method as 或者当我做一个方法
openMydrawer(){
this.drawer.openDrawer();
} }
and then pass it as props to Toolbar as drawer=this.openMyDrawer.bind(this)
and then call it from Toolbar as this.props.openMyDrawer
it works just fine... 然后将其作为道具传递给Toolbar,方式为
drawer=this.openMyDrawer.bind(this)
,然后从工具栏中调用this.props.openMyDrawer
作为它,效果很好...
Can someone explain why undefined is passed when I directly pass reference to Toolbar as objects are passed as reference not by value, as soon as this.drawer gets a value that value should be reflected down to its children or siblings for that matter. 有人可以解释为什么当我直接传递对工具栏的引用时会传递undefined的原因,因为this.drawer获得一个值后,该值应该直接反映给它的子级或同级,因为对象不是按值传递。
The layout function isn't causing a re-render, so when you rendered Toolbar
your this.drawer
was undefined since the layout function wasn't called at this point. 布局功能不会引起重新渲染,因此,在渲染
Toolbar
时,由于此时尚未调用布局功能,因此this.drawer
定义。 Your other method worked because this.drawer
was evaluated at the moment the function ran (button pressed) and not when the component was rendering. 您的其他方法之所以
this.drawer
是因为this.drawer
是在函数运行(按下按钮) this.drawer
不是在渲染组件时评估的。
To pass the ref as a prop, you would have to trigger another render, ideally by putting the ref in the state. 要将ref作为道具传递,您必须触发另一个渲染,最好是将ref置于状态。 Like this:
像这样:
render() {
<DrawerLayoutAndroid
ref={(element) => this.setState({drawer:element})}
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<Toolbar toolbarText="XYZ" drawer={this.state.drawer}/>
</DrawerLayoutAndroid>
}
You should take into account that the drawer ref will be undefined for in Toolbar
's first render. 您应该考虑到在
Toolbar
的第一个渲染中将没有定义抽屉引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.