javascript - 如何将组件传递给 React js 中的组件?
问题描述
我想要做的是传入另一个组件,该组件将使用此语法替换按钮。
<EmailDrop>
<AnotherComponent />
</EmailDrop>
我想一定有办法做到这一点,但我什至不知道要谷歌找出什么。我是否将函数作为道具传递给它?
我觉得我错过了一些非常基本的东西。
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
解决方案
您可以使用 children 道具通过父组件传递子组件。在这种情况下,
<EmailDrop>
<AnotherComponent />
</EmailDrop>
AnotherComponent
是 的children
props 的一部分EmailDrop
,因此,当您处理 的组件逻辑时EmailDrop
,您实际上可以访问AnotherComponent
并有条件地渲染它(如果存在):
render() {
const { children } = this.props;
return (
<>
{
children
? children
: <Buttons />
}
</>
)
}
推荐阅读
- javascript - Reactjs 点击移动到数组中的下一项
- java - i--中的死代码警告
- ffmpeg - ffmpeg 如何在内部工作以从远程视频创建剪辑
- javascript - 页面加载时点击有效
- java - JavaFX 媒体循环
- angular - 使用 RxJS 的 Angular 6 错误:无法读取未定义的属性“调用”
- rx-java - 为什么 Observable.empty() 不向下游传播 onComplete() ?
- reactjs - React Redux 状态变化
- c++ - 无法在 C++ 代码中获得十进制输出。
- java - 这是 IntStream 嵌套循环的最佳选择吗?错误是什么?