简体   繁体   English

如何条件渲染 css inline

[英]How to conditional render css inline

Basically, I can do this because, I conditional render backgroundColor, but I want also render a position. I want some data was display on right, other on left.基本上,我可以这样做是因为,我有条件渲染 backgroundColor,但我还想渲染 position。我希望一些数据显示在右侧,其他数据显示在左侧。 My problem is I have no idea why any of css I used not work: align, alignText, position work halfy float but it cause other thing was destroyed in half.我的问题是我不知道为什么我使用的 css 中的任何一个都不起作用: align, alignText, position工作一半float但它导致其他东西被毁坏了一半。

      {Data.map(i => (
        <StickyContainer
          key={i.id}
          className="container"
        
          style={{  alignText: "right", backgroundImage: `url("/zalety/${i.id}.jpg")`, 
        backgroundSize: "cover", 
    }}
        >
          <Sticky>
            {({ style }) => (
              <h1 style={{ ...style, background:   "#ae4a84", textAlign: "center" }} > {i.title} </h1>
            )}
          </Sticky>

          <h2 className="text-center" style={{width: "45%", backgroundColor:  (i.color ) ? `${i.color} ` : "white",
     
        
        }}>{i.content}</h2>
          
        </StickyContainer>

I tried to use a component such as ExampleCard or something and there put this but it caused error with class/functional component.我尝试使用诸如ExampleCard之类的组件并将其放在那里,但它导致类/功能组件出错。

To conditionally add the inline css, since this is a JS Object that you're passing in to the style props, you can construct the object along with JS spread operator like below:要有条件地添加内联 css,因为这是您传递给样式道具的 JS Object,您可以构造 object 以及 JS 扩展运算符,如下所示:

 ... <h2 className="text-center" style={{width: "45%", backgroundColor: (i.color )? `${i.color} `: "white",...(<condition for right alignment>)?{<CSS props for right alignment>}:{}}>{i.content}</h2>...

Replace the each <> with the appropriate data.将每个 <> 替换为适当的数据。 The above change will make it so that you only apply the CSS when the condition is true.上述更改将使您仅在条件为真时应用 CSS。

For styling and position to the right or left, I usually do something like {position:'absolute', right: 0} but this will only work if your StickyContainer , or whatever the direct parent of your h2 , has a position of relative , otherwise, it will adjust itself with the most recent parent that have the position of relative .对于样式和右侧或左侧的 position,我通常会做类似{position:'absolute', right: 0}操作,但这仅在您的StickyContainerh2的直接父级具有relativeposition ,否则,它会根据具有relativeposition的最近父级进行自我调整。

To future generation, after traing all methods to transform it, just I had a golden shot:对后代来说,想尽办法改造后,正好我有一个千金难求的机会:

transform: (i.position == 'right') ? "translate(100%, 0)" : null,

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

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