【问题标题】:styled-components with custom React components: passing props带有自定义 React 组件的 styled-components:传递道具
【发布时间】:2021-05-01 16:51:30
【问题描述】:

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

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

我想使用 styled-components 对该组件的几个实例应用自定义样式。如何传递 icon 道具以使其仍然起作用(作为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} />
}

谢谢!

【问题讨论】:

    标签: reactjs button components styled-components


    【解决方案1】:

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

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

    起初我尝试将样式传递给 d2l-button-icon 元素,我得到了 icon 属性,但样式被忽略了。

    我让它工作的方法是将样式应用到元素周围的 div 并将其他道具传递给 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 库。

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 2022-06-19
      • 2018-04-27
      相关资源
      最近更新 更多