reactjs 如何改变背景颜色当我点击按钮使用React挂钩

brc7rcf0  于 2023-05-17  发布在  React
关注(0)|答案(3)|浏览(136)

我在React项目工作,在我有App.js组件,在该组件中我有按钮现在请告诉我如何通过使用react hooks更改按钮背景颜色和按钮文本颜色
这是App.js

import React, { useState } from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
      <button className='btn btn-primary'>Click here</button>
    </div>
  );
}

export default App;
r1wp621o

r1wp621o1#

试试这个

function App() {
  const [color,setColor]=useState('red');
  const [textColor,setTextColor]=useState('white');
  return (
    <div className="App">
      <button style={{background:color,color:textColor}} className='btn btn-primary' onClick={()=>{setColor("black");setTextColor('red')}}>Click here</button>
    </div>
  );
}

export default App;

OR检查链接:https://stackblitz.com/edit/react-x7mevv

byqmnocz

byqmnocz2#

App.js

function App() {
  const [toggle,setToggle] = React.useState(false);
  const toggleIt =()=>{
    setToggle(!toggle)
  }
  return (
    <div className="App">
    <button onClick={toggleIt}>{toggle?'Hide':'Show'}</button>
     <div className={toggle&&'body-color'}>
      Body
     </div>
    </div>
  );
}
    • App.css**中的类
.body-color{
  background: coral;
  height:100vh;
}
ruarlubt

ruarlubt3#

import React, { useState } from "react";
import './App.css';

function App() {

 const [color, setColor] = useState("white");  // default value of bg-color 
 const [textColor, setText] = useState("black");  // default value of text-color

 function Clicked() {
  setColor("black");
  setText("white");
  }

  return (
  <div className="App">

  <button
    style={{ background: color, color: textColor }}
    onClick={Clicked}                  // function is called to change the color
    className="btn btn-primary">

     Click here

     </button>
     </div>
     );

相关问题