Using the css-in-js method to add classes to a react component, how do I add multiple components?
使用css-in-js方法向react组件添加类,如何添加多个组件?
Here is the classes variable:
这是classes变量:
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
spacious: {
padding: 10
},
});
Here is how I used it:
这是我如何使用它:
return (
<div className={ this.props.classes.container }>
The above works, but is there a way to add both classes, without using the classNames
npm package? Something like:
上面的工作,但是有没有办法添加两个类,而不使用classNames npm包?就像是:
<div className={ this.props.classes.container + this.props.classes.spacious}>
9
If you want to assign multiple class names to your element, you can use arrays.
如果要为元素指定多个类名,可以使用数组。
So in your code above, if this.props.classes resolves to something like ['container', 'spacious'], i.e. if
所以在上面的代码中,如果this.props.classes解析为['container','spacious']之类的东西,即if
this.props.classes = ['container', 'spacious'];
you can simply assign it to div as
你可以简单地将它分配给div作为
<div className = { this.props.classes.join(' ') }></div>
and result will be
结果将是
<div class='container spacious'></div>
21
you can use string interpolation:
你可以使用字符串插值:
<div className={`${this.props.classes.container} ${this.props.classes.spacious}`}>
5
you can install this package
你可以安装这个包
https://github.com/JedWatson/classnames
https://github.com/JedWatson/classnames
and then use it like this
然后像这样使用它
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'
3
You can also use the extend property (the jss-extend plugin is enabled by default):
您还可以使用extend属性(默认情况下启用jss-extend插件):
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
spaciousContainer: {
extend: 'container',
padding: 10
},
});
// ...
<div className={ this.props.classes.spaciousContainer }>
1
Yes, jss-composes provides you this:
是的,jss-composes为您提供:
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap'
},
spacious: {
composes: '$container',
padding: 10
},
});
And then you just use classes.spacious.
然后你只需使用classes.spacious。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2017/09/06/bdcc7154583e5eed5e39bd4d78f5f48c.html。