如何将道具传递给样式组件中的基础组件? [英] How can I pass props to base component in styled-component?

查看:28
本文介绍了如何将道具传递给样式组件中的基础组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子,假设我有一个可以接受这样的道具的组件:

As an example, let's say I've a component that can take in props like this:

const testComponent = (props: {isBold: boolean}) => {
   if(props.isBold)
     return <strong><div>hello</div></strong>
   return <div>hello</div>
    
}
你好

}

在这种情况下,我的示例组件可以接受 props 并且结果取决于提供给它的 props.

const styledTestComponent = styled(testComponent({isBold: true}))` width: 100%; opacity: 0.5 /* etc etc... */ `

现在,如果我在 styled-components 中扩展这个组件,我如何将我的 props 传递给基础组件?这个想法是这样的:

Well, obviously not going to work. This part will fail: styled(testComponent({isBold: true}))

But the idea is that what I want to do is to use CSS to style a particular instance of a component. So in that case, I will need to pass a pre-defined props to the base component, testComponent.

好吧,显然行不通.这部分将失败:styled(testComponent({isBold: true}))

How can I achieve this?

但是这个想法是我想要做的是使用 CSS 来设置组件的特定实例的样式.因此,在这种情况下,我需要将预定义的 props 传递给基础组件 testComponent.

I've come up with a quick example to illustrate the issue. The code below attempts to style a react component MyCustomImage as a styled-component StyledMyCustomImage. When this is run, you can see that StyledMyCustomImage does render itself as MyCustomImage. However, the CSS styles are not applied.

我怎样才能做到这一点?

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> ); }

我想出了一个简单的例子来说明这个问题.下面的代码尝试将 React 组件 MyCustomImage 设置为样式化组件 StyledMyCustomImage.运行时,您可以看到 StyledMyCustomImage 确实将自身呈现为 MyCustomImage.但是,不应用 CSS 样式.

I've created a sandbox for this demo: https://codesandbox.io/s/k21462vjr5

Oh! Thanks to @SteveHolgado's answer, I've gotten it to work! I didn't know styled component will pass the CSS as a prop to its base component! Here's the code after adding in the class name for future reference:

);}

我为此演示创建了一个沙箱:

The sadnbox of the working demo: https://codesandbox.io/s/j4mk0n8xkw

推荐答案

试试这个,应该可以

const StyledTestComponent = styled(testComponent)`
    width: 100%;
    opacity: 0.5
    /* etc etc... */
`

并以这种方式将道具传递给实例.

and pass the prop to instance in this way.

<StyledTestComponent isBold />

欢迎反馈.我没有检查它是否有效,但感觉它会起作用

Feedbacks are welcome. I have not checked it working, but feels it will work

注意:我检查过,它正在工作.应该适合你.

Note: I checked and it's working. Should work for you.

这篇关于如何将道具传递给样式组件中的基础组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆