Correct way to handle conditional styling in React

前端 未结 9 1107
逝去的感伤
逝去的感伤 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:54

    If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:

    style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
    

    In case 'someCondition' not fulfilled then you pass empty object.

    0 讨论(0)
  • 2020-11-27 04:57

    You can use somthing like this.

    render () {
        var btnClass = 'btn';
        if (this.state.isPressed) btnClass += ' btn-pressed';
        else if (this.state.isHovered) btnClass += ' btn-over';
        return <button className={btnClass}>{this.props.label}</button>;
      }
    

    Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).

    classNames('foo', 'bar'); // => 'foo bar'
    classNames('foo', { bar: true }); // => 'foo bar'
    classNames({ 'foo-bar': true }); // => 'foo-bar'
    classNames({ 'foo-bar': false }); // => ''
    classNames({ foo: true }, { bar: true }); // => 'foo bar'
    classNames({ foo: true, bar: true }); // => 'foo bar'
    
    0 讨论(0)
  • 2020-11-27 05:05

    Another way, using inline style and the spread operator

    style={{
      ...completed ? { textDecoration: completed } : {}
    }}
    

    That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.

    0 讨论(0)
提交回复
热议问题