首页 > 解决方案 > NextJs 将 prop 作为 className 传入

问题描述

我在将道具传递给 className 时遇到了麻烦,我想知道它是否可能。

例如,假设categoryis 传递到函数中并且categoryis "category1"。在 className 中我可以调用styles.category获取styles.category1吗?

export const function ({category}) => {
    return (
      <button className={styles.category}></button>
    )
}
.category1 {
    background: #FF4646 0% 0% no-repeat padding-box;
    opacity: 1;
    width:  200px;
    height: 200px;
    outline: none;
    border: none;
    font: url('../../public/fonts/AirbnbCerealBlack.woff');
    font-size: 20px;
    font-weight:900;
    color: black;
}
    
.category2 {
    background: #4EEA9C 0% 0% no-repeat padding-box;
    opacity: 1;
    width:  270px;
    height: 270px;
    outline: none;
    border: none;
    font: url('../../public/fonts/AirbnbCerealBlack.woff');
    font-size: 20px;
    font-weight:900;
}

标签: htmlcssreactjsnext.js

解决方案


你可以用它styles[category]来设置className你的按钮。

export const function ({ category }) =>{
    return (
        <button className={styles[category]}></button>
    )
}

推荐阅读