将className传递给React组件 [英] Passing in className to React Component
问题描述
我试图将classname
传递给material-ui Button component
,但似乎无法使其正常工作.以下是我的尝试.
I am trying to pass a classname
to the material-ui Button component
but can't seem to get it to work. Below are my attempts.
尝试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>
)}
)}
我也尝试过使用类名npm软件包,但即使这样也不起作用.
I have tried the classnames npm package as well but even that isn't working.
任何帮助将不胜感激,谢谢!
Any help would be appreciated, thanks!
推荐答案
我猜classes
是一个键为button
的对象. //在material-ui示例中,它们将classes
传递为props
I guess classes
is an object with a key as button
. // in material-ui example, they pass classes
as props
稍微更改您的classString
声明.确保您正在传递classes
对象,并且该对象具有名为button
的键.
Change your classString
declaration a bit. Make sure that you are passing classes
object and it has key named 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} ;
更改为
If you are still facing the problem, the issue is with classes
object. To test it change the line const classString = classes.button +
${index};
to
const classString = 'random-class';
并检查按钮是否正在获取类random-class
and check whether the button is getting the class random-class
由于您的classes
对象是这样的:
Since your classes
object is something like this:
{
class1: _class2-something-15443",
class2: ....,
...
}
您应该相应地更改classString
.
将其更改为:
const classString = classes[`class${index}`];
这篇关于将className传递给React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!