问题
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.
Attempt 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:
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.
Any help would be appreciated, thanks!
回答1:
I guess classes
is an object with a key as button
. // in material-ui example, they pass classes
as props
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>
)}
)}
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';
and check whether the button is getting the class random-class
Edit:
Since your classes
object is something like this:
{
class1: _class2-something-15443",
class2: ....,
...
}
you should change classString
accordingly.
change it to:
const classString = classes[`class${index}`];
回答2:
https://reactjs.org/docs/faq-styling.html
className={yourVariableName}
className={'redDiv'}
回答3:
The Material-UI implements CSS-in-js and uses the material-ui/styles 'withStyles' higher order component. Take a look at the Button demo on the site as it's extremely helpful https://material-ui-next.com/demos/buttons/
来源:https://stackoverflow.com/questions/49899542/passing-in-classname-to-react-component