[英]How can I pass props to base component in styled-component?
举个例子,假设我有一个可以接受像这样的道具的组件:
const testComponent = (props: {isBold: boolean}) => {
if(props.isBold)
return <strong><div>hello</div></strong>
return <div>hello</div>
}
在这种情况下,我的示例组件可以接受道具,其结果取决于为其提供的道具。
现在,如果我在样式化组件中扩展此组件,那么如何将我的道具传递到基本组件中? 这个想法是这样的:
const styledTestComponent = styled(testComponent({isBold: true}))`
width: 100%;
opacity: 0.5
/* etc etc... */
`
好吧,显然是行不通的。 这部分将失败: styled(testComponent({isBold: true}))
但是我的想法是,我想做的是使用CSS设置组件的特定实例的样式。 因此,在这种情况下,我需要将预定义的prop传递给基本组件testComponent
。
我该如何实现?
我想出一个简单的例子来说明这个问题。 下面的代码尝试将StyledMyCustomImage
组件MyCustomImage
为样式组件StyledMyCustomImage
。 运行此命令时,您可以看到StyledMyCustomImage
确实将其呈现为MyCustomImage
。 但是,未应用CSS样式。
const MyCustomImage = props => (
<img
src={`https://dummyimage.com/${props.width}x${props.height}/619639/000000`}
/>
);
const StyledMyCustomImage = styled(MyCustomImage)`
border: 2px dotted red;
`;
function App() {
return (
<div className="App">
<h3>Test passing props from styled component to base component</h3>
<StyledMyCustomImage width="600" height="400" />
</div>
);
}
我已经为此演示创建了一个沙箱: https : //codesandbox.io/s/k21462vjr5
哦! 感谢@SteveHolgado的回答,我已经开始工作了! 我不知道样式化组件会将CSS作为道具传递给其基础组件! 下面是添加类名称以供将来参考的代码:
const MyCustomImage = props => (
<img
src={`https://dummyimage.com/${props.width}x${props.height}/619639/000000`}
className={props.className}
/>
);
const StyledMyCustomImage = styled(MyCustomImage)`
border: 2px dotted red;
`;
工作演示的悲伤框: https ://codesandbox.io/s/j4mk0n8xkw
试试这个,它应该工作
const StyledTestComponent = styled(testComponent)`
width: 100%;
opacity: 0.5
/* etc etc... */
`
并以这种方式将道具传递给实例。
<StyledTestComponent isBold />
欢迎反馈。 我没有检查它是否正常工作,但认为它会正常工作
注意:我检查了一下,它可以正常工作了。 应该为您工作。
当使用这样的styled
函数时,包装的组件将传递一个名为className的道具,您需要将其应用于希望样式影响的元素:
const testComponent = (props) => {
return <div className={props.className}>hello</div>
}
您将可以使用自己的样式的所有道具,您可以像这样使用它们:
const styledTestComponent = styled(testComponent)`
width: 100%;
opacity: 0.5;
font-weight: ${props => props.isBold ? "bold" : "normal"};
/* etc etc... */
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.