将className传递给React组件 [英] Passing in className to React Component

查看:1017
本文介绍了将className传递给React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆