我正在使用React和Material-ui,目前正在做类似下面的代码。
有没有更好的办法?
例如,是否有一个函数允许您访问组件下方的“样式” jss对象中的“ props”,该对象最终将通过withStyles()注入到组件中,而不必进行所有这些难看的内联样式设置?
import React from 'react';
import {
MaterialComponentOne,
MaterialComponentTwo,
MaterialComponentThree,
} from '@material-ui/core';
function MyPureComponent(props) {
return (
<MaterialComponentOne
style={
props.type === 'secondary'
? {
css_property: 'css_value1',
}
: {
css_property: 'css_value2',
}
}
className={props.classes.MaterialComponentOne}
position="static"
>
<MaterialComponentTwo>
<MaterialComponentThree
style={
props.type === 'secondary'
? {
css_property: 'css_value1',
}
: {
css_property: 'css_value2',
}
}
variant="title"
className={props.classes.MaterialComponentThree}
>
{props.title}
</MaterialComponentThree>
</MaterialComponentTwo>
</MaterialComponentOne>
);
}
const styles = {
MaterialComponentOne: {
css_property: 'css_value',
css_property: 'css_value',
},
MaterialComponentTwo: {
css_propery: 'css_value',
},
};
export default withTheme()(withStyles(styles)(MyPureComponent));
谢谢。
最佳答案
您可以使用classnames (A simple JavaScript utility for conditionally joining classNames together)。
import React from 'react';
import {
MaterialComponentOne,
MaterialComponentTwo,
MaterialComponentThree,
} from '@material-ui/core';
import classNames from "classnames"
function MyPureComponent(props) {
return (
<MaterialComponentOne
position="static"
className={classNames(
props.classes.MaterialComponentOne,
{[props.classes.classOne]: props.type === 'secondary'},
{[props.classes.classTwo]: props.type !== 'secondary'}
)}
>
<MaterialComponentTwo>
<MaterialComponentThree
variant="title"
className={classNames(
props.classes.MaterialComponentThree,
{"props.classes.classOne": props.type === 'secondary'},
{"props.classes.classTwo": props.type !== 'secondary'}
)}
>
{props.title}
</MaterialComponentThree>
</MaterialComponentTwo>
</MaterialComponentOne>
);
}
const styles = {
MaterialComponentOne: {
css_property: 'css_value',
css_property: 'css_value',
},
MaterialComponentTwo: {
css_propery: 'css_value',
},
classOne: {
css_property: 'css_value',
},
classTwo: {
css_property: 'css_value'
}
};
export default withTheme()(withStyles(styles)(MyPureComponent));
Usage
classNames
函数采用任意数量的参数,可以是字符串或对象。参数'foo'
是{ foo: true}
的缩写。如果与给定键关联的值是伪造的,则该键将不包含在输出中。classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'