【问题标题】:How can I add a Custom component in a Data object?如何在 Data 对象中添加自定义组件?
【发布时间】:2021-09-21 19:28:34
【问题描述】:

我希望 sectionOne 能够调用另一个组件,但我似乎没有做对。基本上下面是我正在尝试做的一个例子。你能帮忙的话,我会很高兴。谢谢

const element = (
  <div label="go Back">
      <Home />
  </div>
);
export const appTabBarQueues = {
  sectionOne: {element},
  sectionTwo: 'Section Two',
  sectionThree: 'Section Three',
  sectionFour: 'Section Four',
  sectionFive: 'Section Five'
};
//drawer.js

import React from 'react';
import PropTypes from 'prop-types';

export const DrawerSection = props => {
    const {sectionOne} = props;
    return (
        <>
            <div>{sectionOne}</div>
        </>
    );
};
DrawerSection.propTypes = {
    sectionOne: PropTypes.any,
};

【问题讨论】:

    标签: javascript reactjs rxjs react-router react-hooks


    【解决方案1】:
    Import React from 'react';
    
    
    const Element = (
          <div label="go Back">
              <Home />
          </div>
        );
    
        export const appTabBarQueues = {
          sectionOne: <Element />,  // Capitals is important else it will be seen as html element
          sectionTwo: 'Section Two',
          sectionThree: 'Section Three',
          sectionFour: 'Section Four',
          sectionFive: 'Section Five'
        };
    
      or
    
     export const appTabBarQueues = {
          sectionOne: React.cloneElement(Element, {someProps: 'something'});
      }
    
      or if its not imported from elsewhere then,
    
      export const appTabBarQueues = {
              sectionOne: function Element(props){
                return <div label="go Back">
                          <Home />
                       </div>
              },
      }
    

    根据您的错误消息提出了一些想法,我进行了一些更改,并且可以看到它有效。检查下面的代码沙箱

    https://codesandbox.io/s/zen-field-1srdo

    【讨论】:

    • 嗨@deechris27 非常感谢您的建议。您的代码确实有意义,但是当我尝试它时,它显示为一个空 div,并且我收到此错误:警告:函数作为 React 子项无效。如果您从渲染返回一个组件而不是 ,则可能会发生这种情况。或者您可能打算调用此函数而不是返回它。
    • 可以粘贴整个组件代码吗? “如果你从渲染返回一个组件而不是 ”。我想你正在使用一个类组件。需要完整代码才能查看上下文和用法。
    • deechris27 我缺少drawer.js 组件。您可以在原始帖子中看到它。
    • 不,这个 appTabBarQueues 用在哪里?我需要那个组件代码。您是否将 appTabBarQueues 作为道具传递给 DrawerSection ?
    • @KarinaTurtle 我已经在我的答案中添加了一个 codesanbox 链接,其中包含工作代码更改。让我知道这是否是您要找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    相关资源
    最近更新 更多