简体   繁体   English

React - 处理动态内联样式的理想方式

[英]React - ideal way to handle dynamic Inline styles

Having this 2 scenarios for handling inline styles, which one is the ideal way to 'toggle' CSS properties depending on the component state - or is a better one? 有两种处理内联样式的方案,哪一种是根据组件状态“切换”CSS属性的理想方式 - 或者是更好的方法?

1. Create a style variable in which you query for the component's state to make a decision, this way you use only one object when assigning the style in your JSX. 1.创建一个样式变量,在其中查询组件的状态以做出决定,这样在JSX中分配样式时只使用一个对象。 see it working here - also this method is not addressed in this top question 看到它在这里工作 - 这个方法也没有在这个顶级问题中解决

render(){
    const style = {
      pStyle : {
        borderRadius: this.state.isCircle ? '50%' : '0px', //query the current state
        height: this.state.isCircle ? '100px' : 'auto', //query the current state
        display: 'inline-block',
        width: '100px',
        textAlign: 'center',
        transition: 'all 0.5s ease-in-out',
        border: 'solid 2px lightblue'
      }
    }
    return(
      <div>
        <p style={style.pStyle} onClick={this.HandleClick}>Hi!</p>

      </div>
    )
}

2. Create more than one object to represent each CSS state of your component, this way you will have to query for the component's state in your JSX and merge the objects with ES6's Object.assign. 2.创建多个对象来表示组件的每个CSS状态,这样您就必须在JSX中查询组件的状态,并将对象与ES6的Object.assign合并。 see it working here 看到它在这里工作

render(){
    const style = {
      pStyle : {
        display: 'inline-block',
        width: '100px',
        textAlign: 'center',
        transition: 'all 0.5s ease-in-out',
        border: 'solid 2px lightblue'
      }, 
      pStyleCircle : { //this will only be applied when state is Circle
        borderRadius: '50%',
        height: '100px',
      }
    }
    return(
      <div>
        <p style={Object.assign({},style.pStyle, this.state.isCircle && style.pStyleCircle)} onClick={this.HandleClick}>Hi!</p>
      </div>
    )
  }

both ways work, but which one should be used over the other, and why? 两种方式都有效,但哪一方应该用于另一方,为什么?

I don't think there's a proper way to do it. 我认为没有一种正确的方法可以做到这一点。 You've a lot of variables here. 你在这里有很多变数。

In my personal and honest opinion I would say the second one is easier to understand and fairly more maintainable and even though I don't like to work with inline style, I would've done something similar with CSS and different modifier classes with just the necessary props. 在我个人和诚实的意见中,我会说第二个更容易理解,更容易维护 ,即使我不喜欢使用内联样式,我也会用CSS和不同的修饰符类做类似的事情。必要的道具。

Just for the record, you can do the same with CSS and classnames . 只是为了记录,你可以用CSS类名做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM