[英]How to add props in react for styles?
I have a simple section in which I want to change the width dynamically我有一个简单的部分,我想在其中动态更改宽度
Here is section这是部分
<div className="form-control">
<Formats>
{styles.map(style => <ButtonStyled type="button" active={style.id === styleId} onClick={() => setStyleId(style.id)} key={`button-${style.name}`}>{style.name}</ButtonStyled>)}
{activeStyle && <FormatsContent>
<FormatsDescription>{activeStyle.desciption}</FormatsDescription>
<Proportions>
{activeStyle.proportions.map(x => <Proportion onClick={() => setProportion(x.proportion)} active={proportion === x.proportion} width={x.width} height={x.height} key={`proportion-${x.proportion}`}>{x.proportionLabel}</Proportion>)}
</Proportions>
</FormatsContent>}
</Formats>
</div>
Here is style这里是风格
const Formats = styled.div`
margin-left: 0px;
padding:12px;
background-color: ${gray.brightest};
border-radius: 20px;
width: 100%;
& select {
height: 31px;
padding: 0;
margin-left: 12px;
}
`;
Now I want to add props to check if width is full or not isFullWidth:true/false
现在我想添加道具来检查宽度是否已满isFullWidth:true/false
and on styles to use it like this,并在 styles 上像这样使用它,
const Formats = styled.div`
margin-left: 0px;
padding:12px;
background-color: ${gray.brightest};
border-radius: 20px;
width: ${props => props.isFullWidth ? '100%' : '59%'}
& select {
height: 31px;
padding: 0;
margin-left: 12px;
}
`;
What do I need to change to achieve what I want?我需要改变什么来实现我想要的?
The Format component should have isFullWidth
prop holding either true
or false
as value as shown below: Format 组件应具有isFullWidth
,该属性为true
或false
,如下所示:
The example below will give a 100%
width下面的示例将给出100%
的宽度
<Format isFullWidth ={true}>
</Format>
And this one will give a 59%
width而这个将给出59%
的宽度
<Format isFullWidth ={false}>
</Format>
I think it is enough to pass the prop to the component and keep the last style you posted:我认为将道具传递给组件并保留您发布的最后一个样式就足够了:
So it should be所以应该是
<Formats isFullWidth>
...
</Formats>
EDIT: wrong prop name编辑:错误的道具名称
Styles interpolation are only available in styled-components
for theming
, if you're not using theme you can pass a prop called theme
to your component, which can be passed down, this way your Component doesn't have to be inside a Provider
Styles 插值仅在styled-components
中可用,如果您不使用theming
,则可以将名为theme
的道具传递给您的组件,该道具可以向下传递,这样您的 Component 不必在Provider
中
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
/* Color the border and text with theme.main */
color: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
`
// Define what main theme will look like
const theme = {
main: "mediumseagreen"
};
render(
<div>
<Button theme={{ main: "royalblue" }}>Ad hoc theme</Button>
<ThemeProvider theme={theme}>
<div>
<Button>Themed</Button>
<Button theme={{ main: "darkorange" }}>Overidden</Button>
</div>
</ThemeProvider>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.