简体   繁体   English

如何在不使用第三方库的情况下通过 React 更改多个样式元素?

[英]How to change multiple style elements through React without using a third party library?

Given that we have a tag as such:鉴于我们有这样的标签:

<video style={{ background: "blue", width: "111px", height: "111px" }} />

It is easy to manipulate one element such as width like this:像这样操作一个元素(例如width )很容易:

<video style={{ background: "blue", width: state ? '100px' : '200px', height: "111px" }} />

However if I want to change both of them upon changing the state I have to copy it over as such:但是,如果我想在更改state时同时更改它们,我必须将其复制过来:

<video style={{ background: "blue", width: state ? '100px' : '200px', height: state ? '100px' : '200px' }} />

And I suspect this is not the way to go.而且我怀疑这不是通往 go 的方法。

How to change multiple style elements without repeating myself over and over again?如何更改多个样式元素而不一遍又一遍地重复自己?

Are you using CSS directly?您是直接使用 CSS 吗?

If you're, consider doing something like this with class如果你是,考虑用 class 做这样的事情

// CSS in a index.css file
.has-state {
 height: 100px;
 width: 100px;
}

.no-state {
  height: 200px;
  width: 200px;
}

.has-state, .no-state {
  background: "blue"
}
// in the React file e.g. index.ts
import * as React from "react";
import "./index.css";

const Component = () => (
  <video className={state ? "has-state" : "no-state"} />
)

Put the logic above the jsx:将逻辑放在jsx之上:

const stateStyles = state 
  ? {
      width: '100px',
      height: '100px',
      border: '2px solid black'
    } 
  : {
      width: '200px',
      height: '200px'        
    };

return (
  <video style={{ background: "blue", ...stateStyles }} />
)

暂无
暂无

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

相关问题 如何在没有任何第三方库的情况下使用javascript将html div元素内的所有元素转换为图像 - How to convert all elements inside html div element into an image using javascript without any third party library 如何在不使用第三方库的情况下将 html 字符串转换为反应元素? - How do I convert a html string into a react element without using a third party library? 更改第三方 iframe 的样式 - Change style of a third party iframe 如何使用 jest 模拟第三方库 - How to mock third party library using jest 在没有第三方库的情况下反应 js 无限滚动 - react js infinite scroll without third party library Javascript / CSS-如何在没有第三方JS库的情况下更改textarea滚动条的颜色? - Javascript/CSS- how to change the colour of a textarea scrollbar without a third party JS library? 如何在单个 React 组件中为第三方组件应用自定义样式而不影响其在其他组件中的样式? - How to I apply a custom style for a third-party component in a single React component without affecting its style in other components? 使用第三方库与React js给出错误 - Using third party library with react js giving error 创建一个无需使用第三方库即可接受脚本(javascript)的控件 - create a control to accept script (javascript) without using third party library 不使用第三方库即可在angular js中导出Excel - Export excel in angular js without using third party library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM