Correct way to handle conditional styling in React

前端 未结 9 1235
逝去的感伤
逝去的感伤 2020-11-27 04:25

I\'m doing some React right now and I was wondering if there is a \"correct\" way to do conditional styling. In the tutorial they use

style={{
  textDecorati         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 04:47

    If you prefer to use a class name, by all means use a class name.

    className={completed ? 'text-strike' : null}
    

    You may also find the classnames package helpful. With it, your code would look like this:

    className={classNames({ 'text-strike': completed })}
    

    There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.

    POSTSCRIPT [06-AUG-2019]

    Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.

提交回复
热议问题