首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将多个className作为道具传递

将多个className作为道具传递
EN

Stack Overflow用户
提问于 2019-12-26 03:29:45
回答 2查看 64关注 0票数 1

我有一个使用css模块作为样式方法的模块化组件,比如说component.jscomponent.module.scss。我想要实现的是使用带有className的组件作为工具。

代码语言:javascript
运行
复制
// component.js

import React from 'react';
import Style from './grid.module.scss';

const Grid = (props) => {
    return(
        <div className={`${Style[props.test]}`}>
            {props.children}
        </div>
    )
}

export default Grid;
代码语言:javascript
运行
复制
// component.module.scss

.foo {
  // some style here...
}

.bar {
  // some style here...
}

问题是,如果属性有多个类名,Style[props.test]就不能工作。

例如

代码语言:javascript
运行
复制
// index.js

import React from 'react';
import Grid from './component';

// Working
<Grid test="a">Baz</Grid> // the output is class="a--3ofml"

// doesnt work
<Grid test="a b">Baz</Grid>  // the output is class="undefined"

如何让代码与多个属性值一起工作?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-26 03:44:38

看起来你可以这样做:

代码语言:javascript
运行
复制
return (
   <div className={
      props.test.split(' ').map(s => `${Style[s]}`).join(' ')
    }>
      {props.children}
   </div>
)

Used this as a reference.

票数 3
EN

Stack Overflow用户

发布于 2019-12-26 03:42:29

代码语言:javascript
运行
复制
const Grid = (props) => {
    let cls = props.test.split(" ");
    let styleNames = "";
    cls.forEach(el => {
        styleNames = styleNames + Style[el] + " ";
    })
    return (
        <div className={styleNames}>
            {props.children}
        </div>
    )
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59481299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档