美文网首页
react 动态修改 class 和 style

react 动态修改 class 和 style

作者: 暴躁程序员 | 来源:发表于2022-04-01 11:02 被阅读0次

1. 动态修改 class

1. 动态修改class

  1. 新建 test.css
.bgblue {
  width: 200px;
  height: 200px;
  background-color: rgb(123, 181, 233);
  font-size: 30px;
  font-weight: bold;
}
.bgred {
  width: 200px;
  height: 200px;
  background-color: rgb(233, 123, 123);
}
  1. 在模板中定义className(与条件渲染的方式类似)

方式一:函数抽离(适合多条件判断)

import "./test.css";
const status = "1";
function changeBg() {
  if (status === "1") {
    return "bgblue";
  } else {
    return "bgred";
  }
}

function App() {
  return (
    <div>
       <div className={changeBg()}>函数抽离修改class</div>
    </div>
  );
}

export default App;

方式二:运算符判断

import "./test.css";
const status = "1";

function App() {
  return (
    <div>
      <div className={(status === "1" && "bgblue") || "bgred"}>
          运算符修改class
        </div>
    </div>
  );
}

export default App;

方式三:三元运算判断

import "./test.css";

function App() {
  return (
    <div>
      <div className={status === "1" ? "bgblue" : "bgred"}>三元运算修改class</div>
    </div>
  );
}

export default App;

2. 在列表渲染中动态修改 class

import "./test.css";
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const listEl = list.map((item, index) => {
  return (
    <div key={index} className={index % 2 === 0 ? "bgblue" : "bgred"}>
      {item}
    </div>
  );
});

function App() {
  return (
    <div>
      <div>{listEl}</div>
    </div>
  );
}

export default App;

3. 动态添加多个 class

将 class 类名,以空格的方式隔开

import "./test.css";
const status = "2";
function changeBg() {
  if (status === "1") {
    return "bgblue";
  } else {
    return "bgred bgblue";
  }
}

function App() {
  return (
    <div>
       <div className={changeBg()}>动态添加多个class</div>
    </div>
  );
}

export default App;

2. 动态修改 style

style 内的属性需要以对象的方式呈现,且 - 连接的属性,需要改成驼峰式命名

const status = "2";
function changeBg() {
  if (status === "1") {
    return { color: "red", backgroundColor: "rgb(123, 181, 233)" };
  } else {
    return { color: "blue", backgroundColor: "rgb(233, 123, 123)" };
  }
}

function App() {
  return (
    <div>
       <div style={changeBg()}>动态修改style</div>
    </div>
  );
}

export default App;

相关文章

网友评论

      本文标题:react 动态修改 class 和 style

      本文链接:https://www.haomeiwen.com/subject/ozynjrtx.html