reactjs - 带有自定义 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} />
}
谢谢!
解决方案
这是一个非常不寻常的情况,因为d2l-button-icon
您正在处理自定义 HTML 元素而不是 React 组件。
styled-components
可以为任何 React 组件和任何内置 DOM 元素( , 等)设置样式a
,div
但我认为它不知道如何处理自定义 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 库。
推荐阅读
- mysql - SQL - 每个 id 只显示一行
- reactjs - React HOC 的不变违规
- sql-server - 使用带有 SQL 联合的过滤器
- c - 如何让子线程等待主线程
- assembly - 如何使用 BIOS 中断设置引导分区
- mysql - MYSQL 查询将 16 行拆分为 2 个团队
- sql-server - 使用节点 js 将多列和多行插入 SQL Server
- ansible - Ansible 环境变量或默认值
- javascript - 将角度依赖项从 1.5 升级到 1.7 后,console.error() 抛出未定义的错误?
- c# - SystemArgumentOutOfRangeException C#