如何在点击按钮时同时调用两个函数?



在这个叫做buttons的组件中有4个按钮。当它们被按下时,它们将是计数器++,这意味着数字将增加1。当数字改变时,颜色也应该改变。我不能改变颜色。

import { useState } from "react";
import "./App.css";
import Buttons from "./components/Buttons";
import Counter from "./components/Counter";
function App() {
const [counter, setCounter] = useState(0);
const [counterColor, setcounterColor] = useState("");

const changeCounter = (n) => {
return setCounter(n + 1);
};
const arr = ["red", "green", "blue", "yellow"];

const changeColor = () => {
return setcounterColor(arr[0 + 1]);
};

console.log(counter);
return (
<div className="App">
<Counter
counter={counter}
clazz={counterColor}
/>
<Buttons
changeCounter={() => changeCounter(counter)}
changeColor={changeColor}
/>
</div>
);
}
export default App;
function Buttons({ changeCounter, changeCounterColor }) {
return (
<div>
<button onClick={(changeCounter, changeCounterColor)}>Click</button>{" "}
<button onClick={changeCounter}>Click</button> <button onClick={changeCounter}>Click</button>{" "}
<button onClick={changeCounter}>Click</button>{" "}
</div>
);
}
export default Buttons;

如果您想在点击按钮后调用changeCounterchangeCounterColor,您可以这样做:

<button
onClick={() => {
changeCounter(1);
changeCounterColor(1);
}}
>
Click
</button>

要改变计数器的颜色,将changeCouterColor更改为:

const changeColor = (n) => {
return setcounterColor(arr[n-1]);
};

相关内容

  • 没有找到相关文章

最新更新