我试图从closeBtn
DOM调用DrawerItem
方法。由于它是ToggleDrawer
的子组件,DrawerItem
如何才能访问closeBtn
方法?
class Header extends React.Component {
//no method here
render() {
return (
...
<ToggleDrawer
icon_class="notify-toggle"
alignment="right"
icon_link={Url.urlForStatic('images.g')} ...
>
<DrawerItem text="Alert 1" />
<DrawerItem text="Alert 2" />
<DrawerItem text="Alert 3" />
</ToggleDrawer>
这是ToggleDrawer类。
class ToggleDrawer extends React.PureComponent {
...
closeDrawer() { //I want to call this method from DrawerItem.
//so that once user clicks the item, it closes the drawer.
this.ref.hide();
}
...
这是DrawerItem
class DrawerItem extends React.PureComponent {
render() {
console.log(this.props); // <- How can I get this.props.closeBtn method here?
return (
<div className="drawer-item">
<BinaryLink to={this.props.link_to}>
<span ...>{this.props.text}</span>
</BinaryLink>
</div>
);
}
}
答案 0 :(得分:0)
简单的方法就是你应该为DrawerItem创建closeDrawer prop并通过 DrawerItem
的道具推送 closeDrawer()BAR_*
答案 1 :(得分:0)
我认为如果你不使用Redux,你应该处理ToggleDrawer之外的state,方法。为什么不制作像ToggleDrawerContainer这样的组件,并将方法作为道具传递给DrawerItem。
class ToogleDrawerContainer extends React.Component {
closeDrawer(){};
<ToggleDrawer
icon_class='notify-toggle'
alignment='right'
icon_link={Url.urlForStatic('images.g')}...
>
<DrawerItem closeDrawer={this.closeDrawer} text='Alert 1'/>
</ToggleDrawer>
}
答案 2 :(得分:0)
声明toggleDrawer:ToggleDrawer
<ToggleDrawer
ref={tg => {
if (tg) this.toggleDrawer = tg;
}}
icon_class="notify-toggle"
alignment="right"
icon_link={Url.urlForStatic('images.g')} ...
>
<DrawerItem
closeDrawer={this.toggleDrawer ? this.toggleDrawer.closeDrawer : () => {}}
text="Alert 1"
/>
<DrawerItem
closeDrawer={this.toggleDrawer ? this.toggleDrawer.closeDrawer : () => {}}
text="Alert 1"
/>
<DrawerItem
closeDrawer={this.toggleDrawer ? this.toggleDrawer.closeDrawer : () => {}}
text="Alert 1"
/>
</ToggleDrawer>;