首页 > 解决方案 > 如何将组件传递给 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

标签: javascriptreactjsreact-component

解决方案


您可以使用 children 道具通过父组件传递子组件。在这种情况下,

<EmailDrop>
  <AnotherComponent />
</EmailDrop>

AnotherComponent是 的childrenprops 的一部分EmailDrop,因此,当您处理 的组件逻辑时EmailDrop,您实际上可以访问AnotherComponent并有条件地渲染它(如果存在):

render() {
  const { children } = this.props;  

  return ( 
    <>
      {
        children 
         ? children 
         : <Buttons /> 
      }
    </>
  )
}

推荐阅读