【问题标题】:How to add custom icon to tree and treenode如何将自定义图标添加到树和树节点
【发布时间】:2019-07-19 11:39:21
【问题描述】:

我正在使用 antd tree ui 组件构建一棵树,并且想将我自己的图标示例 something.png 或 jpg 文件添加到每个 treeNode。我是怎么做到的,请帮忙?

【问题讨论】:

    标签: reactjs antd


    【解决方案1】:

    Tree 接受名为 switcherIcon 的道具,TreeNode 接受名为 icon 的道具。提到的道具可以是任何有效的ReactNodeFunction(props):ReactNode。通常最好使用 antd 提供的默认Icon 组件,但您也可以使用自己的<img/>

    使用 antd 的示例Icon

    <Tree
      showIcon
      defaultExpandAll
      defaultSelectedKeys={['0-0-0']}
      switcherIcon={<Icon type="down" />}
    >
      <TreeNode icon={<Icon type="smile-o" />} title="parent 1" key="0-0">
        <TreeNode icon={<Icon type="meh-o" />} title="leaf" key="0-0-0" />
        <TreeNode icon={<Icon type="meh-o" />} title="leaf" key="0-0-1" />
      </TreeNode>
    </Tree>
    

    使用您自己的自定义图像:

    首先定义你的组件:

    const CustomIcon = () => (
      <img
        style={{ width: 15, padding: 1 }} // some custom style to look good
        src="https://image.flaticon.com/icons/svg/109/109688.svg" // use your imported .png or .jpg file instead
        alt="Custom Icon"
      />
    );
    

    然后和前面的例子一样使用:

    <Tree
      showIcon
      defaultExpandAll
      defaultSelectedKeys={['0-0-0']}
      switcherIcon={<CustomIcon />}
    >
      <TreeNode icon={<CustomIcon />} title="parent 1" key="0-0">
        <TreeNode icon={<CustomIcon />} title="leaf" key="0-0-0" />
        <TreeNode icon={<CustomIcon />} title="leaf" key="0-0-1" />
      </TreeNode>
    </Tree>
    

    这是一个沙盒演示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2022-06-13
      • 1970-01-01
      • 2012-02-10
      • 2012-10-19
      相关资源
      最近更新 更多