[英]How to modify CSS using JavaScript in React.js
如何在 React 上使用 JavaScript 更改 css 樣式?
例如,我會這樣做:
document.querySelector('.container').style.backGroundColor='purple';
}
這樣對嗎 ? 或者我應該用另一種方式來做嗎?
您可以使用樣式屬性。
<SomeComponent style={{
backgroundColor: someCondition ? 'purple' : null
}} />
考慮段落元素
document.getElementsByClassName("container").style.color = "blue";
像這樣創建一個 const 類型的 obj(必須在渲染方法中創建)
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
並像這樣將其分配到您的元素中
h1 style={mystyle}>Hello Style!</h1>
在 Reactjs 中更改 css 的簡單方法是Inline styling
。 您可以在以下位置查看其他方式: https : //codeburst.io/4-four-ways-to-style-react-components-ac6f323da822
舉個例子。 如果您想更改用戶狀態的顏色。 活動將是綠色或非活動將是紅色。
const Example = (props) => {
let isActive = Math.floor(Math.random() * 2) % 2 === 0;
const color = isActive ? 'green' : 'red';
return <div style={{backgroundColor: color}}> {isActive ? 'Active' : 'Deactive'} </div>;
}
或者:
const Example = (props) => {
let isActive = Math.floor(Math.random() * 2) % 2 === 0;
return <div style={{backgroundColor: isActive ? 'green' : 'red'}}> {isActive ? 'Active' : 'Deactive'} </div>;
}
或所有樣式:
const Example = (props) => {
let isActive = Math.floor(Math.random() * 2) % 2 === 0;
let styleStatus = isActive ?
{
backgroundColor: 'green',
fontSize: '20',
} :
{
backgroundColor: 'red',
fontSize: '15',
};
return <div style={styleStatus}> {isActive ? 'Active' : 'Deactive'} </div>;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.