首页 > 解决方案 > 带有自定义 React 组件的 styled-components:传递道具

问题描述

我有一个自定义组件,它接受一个属性图标并将按钮的内部图像设置为相应的图标,如下所示:

<custom-button-icon ref={showIcon} slot="right" icon="tier1:visibility-show" onClick={() => isPasswordVisible(false)} />

我想使用 styled-components 将自定义样式应用于此组件的几个实例。如何传递 icon 道具以使其仍然起作用(作为 pop 传入custom-button-icon)?这是我到目前为止所拥有的,但它返回一个空按钮(没有图标):

export const d2lButtonIcon = ({ icon }) => {
  const buttonIcon = styled(`d2l-button-icon`)`
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 100px;
    margin: 1px;
`
  return <buttonIcon icon={icon} />
}

谢谢!

标签: reactjsbuttoncomponentsstyled-components

解决方案


这是一个非常不寻常的情况,因为d2l-button-icon您正在处理自定义 HTML 元素而不是 React 组件。

styled-components可以为任何 React 组件和任何内置 DOM 元素( , 等)设置样式adiv但我认为它不知道如何处理自定义 DOM 元素,因为这不是我们在 React 中构建事物的方式。

起初我尝试将样式传递给d2l-button-icon元素,我让icon道具通过但样式被忽略了。

我让它工作的方式是将样式应用于div元素周围的 a 并将其他道具传递给d2l-button-icon元素本身。

// function component adds styles around the icon button
const UnstyledD2L = ({ className, ...props }) => {
  return (
    <div className={className}>
      <d2l-button-icon {...props} />
    </div>
  );
};

// can use styled-component to style this wrapper component
const StyledButtonIcon = styled(UnstyledD2L)`
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100px;
  margin: 1px;
`;

// example usage with props
export default () => <StyledButtonIcon text="My Button" icon="tier1:gear" />;

但是,如果您不喜欢这个 Brightspace 包,我建议您切换到专为 React 设计的 UI 库。


推荐阅读