简体   繁体   English

如何基于条件将属性应用或不应用于 jsx 元素

[英]How to based in a condition apply or not a property into a jsx element

I have this element:我有这个元素:

<div id="app-wrapper" style={{"grid-template-columns": "50% 50%"}}>..</div>

I want to based on a condition defined in my component's state change the style property to this:我想根据组件状态中定义的条件将样式属性更改为:

<div id="app-wrapper" style={{"grid-template-columns": "100%"}}>..</div>

You can conditionally render the style using a ternary operator in 2 ways:您可以通过两种方式使用三元运算符有条件地呈现样式:

Option 1:选项1:

<div id="app-wrapper" style={state? {"grid-template-columns": "50% 50%"} : {"grid-template-columns": "100%"}}>..</div>

Option 2 (cleaner):选项 2(更清洁):

const divStyle = state? {"grid-template-columns": "50% 50%"} : {"grid-template-columns": "100%"}


<div id="app-wrapper" style={divStyle}>..</div>

您喜欢使用三元运算符:

<div id="app-wrapper" style={{"grid-template-columns": condition?"100%":"50% 50%"}}>..</div>

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

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