简体   繁体   English

将className传递给React组件

[英]Passing in className to React Component

I am trying to pass a classname to the material-ui Button component but can't seem to get it to work. 我试图将一个classname传递给material-ui Button component但似乎无法使其正常工作。 Below are my attempts. 以下是我的尝试。

Attempt 1 : 尝试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>
  )}
)}

Attempt 2 : 尝试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>
  )}
)}

I have tried the classnames npm package as well but even that isn't working. 我也尝试过使用classnames npm包,但即使这样也不起作用。

Any help would be appreciated, thanks! 任何帮助,将不胜感激,谢谢!

I guess classes is an object with a key as button . 我猜classes是一个带有键作为button的对象。 // in material-ui example, they pass classes as props //在material-ui示例中,它们将classes作为props传递

Change your classString declaration a bit. classString更改classString声明。 Make sure that you are passing classes object and it has key named button . 确保您正在传递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>
  )}
)}

If you are still facing the problem, the issue is with classes object. 如果仍然遇到问题,则问题出在classes对象上。 To test it change the line const classString = classes.button + ${index} ; 要对其进行测试,请更改const classString = classes.button + $ {index}行; to

const classString = 'random-class';

and check whether the button is getting the class random-class 并检查按钮是否获得random-class

Edit: 编辑:

Since your classes object is something like this: 由于您的classes对象是这样的:

{
  class1: _class2-something-15443",
  class2: ....,
  ...
}

you should change classString accordingly. 您应该相应地更改classString

change it to: const classString = classes[`class${index}`]; 更改为: const classString = classes[`class${index}`];

https://reactjs.org/docs/faq-styling.html

  • className={yourVariableName}
  • className={'redDiv'}

The Material-UI implements CSS-in-js and uses the material-ui/styles 'withStyles' higher order component. Material-UI实现CSS-in-js,并使用material-ui / styles'withStyles'高阶组件。 Take a look at the Button demo on the site as it's extremely helpful https://material-ui-next.com/demos/buttons/ 看一下网站上的Button演示,因为它非常有用https://material-ui-next.com/demos/buttons/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM