Correct way to handle conditional styling in React

前端 未结 9 1234
逝去的感伤
逝去的感伤 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: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 ;
      }
    

    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'
    

提交回复
热议问题