最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React adds an "undefined" class to components - Stack Overflow

programmeradmin0浏览0评论

I have multiple ponents in my project, most of which are simple containers for specific content, with a bit of styling. They typically look like this—

function Portion(props) {
    return (
        <div id={props.id} className={`portion ${props.className}`}>
            {props.children}
        </div>
    )
}

I have the extra ${props.className} so that it’s easy to add more classes if need be. Now, the problem is that if there are no extra classes for that element, React adds an undefined class.

How can I avoid that?

I have multiple ponents in my project, most of which are simple containers for specific content, with a bit of styling. They typically look like this—

function Portion(props) {
    return (
        <div id={props.id} className={`portion ${props.className}`}>
            {props.children}
        </div>
    )
}

I have the extra ${props.className} so that it’s easy to add more classes if need be. Now, the problem is that if there are no extra classes for that element, React adds an undefined class.

How can I avoid that?

Share Improve this question asked Apr 22, 2019 at 11:14 Sujan SundareswaranSujan Sundareswaran 2,5512 gold badges14 silver badges26 bronze badges 2
  • initialize props.className="" – Oram Commented Apr 22, 2019 at 11:17
  • set default prop values – Junius L Commented Apr 22, 2019 at 11:18
Add a ment  | 

3 Answers 3

Reset to default 6

Try using

${props.className || ""}

you can add a condition;

className={`portion ${props.className || ””}`}

You can add a default value to the className if you destructure your props

function Portion({className = '', id, children}) {
    return (
        <div id={id} className={`portion ${className}`}>
            {children}
        </div>
    )
}
发布评论

评论列表(0)

  1. 暂无评论