【问题标题】:AntD Tree: need help! can't pass react element as icon OR title for antd treeAntD 树:需要帮助!不能将 React 元素作为图标或标题传递给 antd 树
【发布时间】:2022-11-13 13:08:21
【问题描述】:

我正在使用 AntD 树,并且我有一个想要作为图标或标题传递的反应元素,因为它具有自定义样式。由于它是 IP,我无法共享太多代码,但我的问题是: 如何将反应元素(见下文,即通用名称)作为标题或图标传递并让 antD 树呈现它?

即这是我想作为道具传递给图标或标题的内容

import React from 'react';

const genericName = (props) => {
  // code uses props to get some infor for Color
  // cant share code due to proprietary reasons
  // but it is not needed for this question
  
    const colorHTML = getColor(Color);

    return (
        <div>
            <div className={`colors from`}>${colorHTML}</div>
            {pin}
        </div>
    );
};

export default genericName;

在我的控制台中,您可以看到 node.icon 是 react.element 类型。我想以此为目标,只需将道具作为标题或图标传递给 antD 树

IE。

return (
  <Tree
    icon={node.icon}
    />
  )

在antD禁止使用children并严格允许treeData之前,我已经搜索并给出了类似的答案。我看到的所有示例都只在标题/图标中使用字符串,但由于 antD 文档非常有限,我需要知道我的用例是否可行。现在,对于我的生活,我无法理解为什么它没有填充。

先感谢您。

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    将 JSX 组件作为title 放在treeData 中肯定会起作用。看看这个 sn-p,我在其中一个标题中添加了一个图标:

    import React from 'react'
    
    
    import  { RightCircleOutlined } from '@ant-design/icons'
    
    type Props = {}
    
    import { Tree } from 'antd';
    import type { DataNode, TreeProps } from 'antd/es/tree';
    
    const treeData: DataNode[] = [
      {
        title: <span>{<RightCircleOutlined />} parent</span>, //icon added here
        key: '0-0',
        children: [
          {
            title: 'parent 1-0',
            key: '0-0-0',
            disabled: true,
            children: [
              {
                title: 'leaf',
                key: '0-0-0-0',
                disableCheckbox: true,
              },
              {
                title: 'leaf',
                key: '0-0-0-1',
              },
            ],
          },
          {
            title: 'parent 1-1',
            key: '0-0-1',
            children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
          },
        ],
      },
    ];
    
    const Demo: React.FC = () => {
      const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
      };
    
      const onCheck: TreeProps['onCheck'] = (checkedKeys, info) => {
        console.log('onCheck', checkedKeys, info);
      };
    
      return (
        <Tree
          checkable
          defaultExpandedKeys={['0-0-0', '0-0-1']}
          defaultSelectedKeys={['0-0-0', '0-0-1']}
          defaultCheckedKeys={['0-0-0', '0-0-1']}
          onSelect={onSelect}
          onCheck={onCheck}
          treeData={treeData}
        />
      );
    };
    
    export default Demo;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多