将道具传递给实质性的UI风格 [英] Passing props to material UI style
问题描述
给出的卡代码如下:卡
我怎样才能更新卡片样式或任何重要的UI样式?
how can I update the card style or any material UI style as from
const styles = theme => ({
card: {
minWidth: 275,
},
如下:
const styles = theme => ({
card: {
minWidth: 275, backgroundColor: props.color },
当我尝试最新版本时,我得到了
when I tried the latest one, I got
Line 15: 'props' is not defined no-undef
当我将代码更新为:
const styles = theme => (props) => ({
card: {
minWidth: 275, backgroundColor: props.color },
也
const styles = (theme ,props) => ({
card: {
minWidth: 275, backgroundColor: props.color },
代替
const styles = theme => ({
card: {
minWidth: 275, backgroundColor: props.color },
我在网页上弄乱了组件卡的样式.
I got the component card style at the web page messy.
顺便说一下,我传递道具如下:
By the way, I pass props as follows:
<SimpleCard backgroundColor="#f5f2ff" />
请帮助!
推荐答案
由@Hugo Gresse此答案是太old和MUI现在提供了将道具传递给makeStyles
函数的方法,请参见此答案.
Edit by @Hugo Gresse: this answer is too old and MUI now offer ways to pass props to the makeStyles
function, see this answer.
使用withStyles
时,您可以访问theme
,但不能访问props
.
When you're using withStyles
, you have access to the theme
, but not props
.
请注意,在Github请求上有一个公开问题此功能以及一些评论可能会为您提供您可能感兴趣的替代解决方案.
Please note that there is an open issue on Github requesting this feature and some of the comments may point you to an alternative solution that may interest you.
使用道具更改卡片背景颜色的一种方法是使用内联样式设置此属性.我已对您的原始代码框进行了分叉,您可以查看
One way to change the background color of a card using props would be to set this property using inline styles. I've forked your original codesandbox with a few changes, you can view the modified version to see this in action.
这就是我所做的:
- 使用
backgroundColor
道具渲染组件:
- Render the component with a
backgroundColor
prop:
// in index.js
if (rootElement) {
render(<Demo backgroundColor="#f00" />, rootElement);
}
- 使用此道具将内联样式应用于卡片:
function SimpleCard(props) {
// in demo.js
const { classes, backgroundColor } = props;
const bull = <span className={classes.bullet}>•</span>;
return (
<div>
<Card className={classes.card} style={{ backgroundColor }}>
<CardContent>
// etc
现在,呈现的卡片组件具有红色(#F00)背景
Now the rendered Card component has a red (#F00) background
请参阅文档的替代部分,以了解其他选项.
Take a look at the Overrides section of the documentation for other options.
这篇关于将道具传递给实质性的UI风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!