What I want to be able to do is pass in another component that would replace the buttons using this syntax.
<EmailDrop>
<AnotherComponent />
</EmailDrop>
I imagine there must be a way to do this but I am struggling to even know what to google to find out. Do I pass a function into it as a prop?
I feel like I am missing something really basic.
import React, { Component } from 'react';
class EmailDrop extends Component {
constructor() {
super();
this.state = {
showMenu: false,
};
this.showMenu = this.showMenu.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
showMenu(event) {
event.preventDefault();
this.setState({ showMenu: true }, () => {
document.addEventListener('click', this.closeMenu);
});
}
closeMenu(event) {
if (!this.dropdownMenu.contains(event.target)) {
this.setState({ showMenu: false }, () => {
document.removeEventListener('click', this.closeMenu);
});
}
}
render() {
return (
<div>
<button onClick={this.showMenu}>
Show menu
</button>
{
this.state.showMenu
? (
<div
className="menu"
ref={(element) => {
this.dropdownMenu = element;
}}
>
<button> Menu item 1 </button>
<button> Menu item 2 </button>
<button> Menu item 3 </button>
</div>
)
: null
}
</div>
);
}
}
export default EmailDrop
You can pass down child components through a parent component using the children props. In this scenario,
<EmailDrop>
<AnotherComponent />
</EmailDrop>
AnotherComponent
is part of the children
props of EmailDrop
, and therefore, when you are working on the component logic for EmailDrop
, you can actually access AnotherComponent
and conditionally render it if it exists:
render() {
const { children } = this.props;
return (
<>
{
children
? children
: <Buttons />
}
</>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.