[英]Passing in className to React Component
我试图将一个classname
传递给material-ui Button component
但似乎无法使其正常工作。 以下是我的尝试。
尝试1 :
attributes.map((attribute, index) => {
const classString = 'classes.button' + index;
console.log(classString)
return (
<Button className={classString} onClick={this.handleClick.bind(this, attribute)}>
{attribute}
</Button>
)}
)}
尝试2 :
attributes.map((attribute, index) => {
const classString = 'classes.button' + index;
console.log(classString)
return (
<Button className={'${classString}'} onClick={this.handleClick.bind(this, attribute)}>
{attribute}
</Button>
)}
)}
我也尝试过使用classnames npm包,但即使这样也不起作用。
任何帮助,将不胜感激,谢谢!
我猜classes
是一个带有键作为button
的对象。 //在material-ui示例中,它们将classes
作为props
传递
classString
更改classString
声明。 确保您正在传递classes
对象,并且它具有名为button
。
attributes.map((attribute, index) => {
const classString = classes.button + `${index}`; // best practice to add string to a number
return (
<Button className={classString} onClick={this.handleClick.bind(this, attribute)}>
{attribute}
</Button>
)}
)}
如果仍然遇到问题,则问题出在classes
对象上。 要对其进行测试,请更改const classString = classes.button +
$ {index}行;
至
const classString = 'random-class';
并检查按钮是否获得random-class
编辑:
由于您的classes
对象是这样的:
{
class1: _class2-something-15443",
class2: ....,
...
}
您应该相应地更改classString
。
更改为: const classString = classes[`class${index}`];
https://reactjs.org/docs/faq-styling.html
className={yourVariableName}
className={'redDiv'}
Material-UI实现CSS-in-js,并使用material-ui / styles'withStyles'高阶组件。 看一下网站上的Button演示,因为它非常有用https://material-ui-next.com/demos/buttons/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.