[英]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.