簡體   English   中英

單擊 Reactjs 時如何更改按鈕顏色

[英]How change button color when clicked Reactjs

我有這樣一個項目。 在這里,我希望單擊按鈕時顏色會發生變化。 這些按鈕分為幾類。 但是有這樣一個問題,當我點擊的時候,所有的colors都變了。 我只想更改與我選擇的類別對應的按鈕的顏色。 我該如何解決?

 import React, { useEffect, useState } from "react"; import SpinnerLoad from './components/SpinnerLoad' import NewsItem from "./components/NewsItem"; import Category from "./components/data/Category" const App = () => { const [state, setState] = useState([]); const [loading, setLoading] = useState(false) const [btnColor, setBtnColor] = useState("black"); const setColor = () =>{ setBtnColor('red') } const fetchValue = (category) => { localStorage.setItem("category", category); fetch(`https://inshorts-api.herokuapp.com/news?category=${category}`).then(res => res.json()).then(res => { setState(res.data) setLoading(true) }).catch((error) => console.log(error)) setLoading(false); }; const CategoryButton = ({ category }) => ( <button onClick={() => { fetchValue(category); setColor() }} style={{ textTransform: 'capitalize',color:btnColor }} >{category}</button> ); useEffect(() => { let categoryValue = localStorage.getItem("category") || "all"; fetchValue(categoryValue) },[]); return ( <> <div className="header-bg"> <h1 className="mb-3">News</h1> <div className="btns "> {Category.map((value, index) => { return <CategoryButton category={value} key={index} />; })} </div> </div> <div className="news"> <div className="container"> <div className="row"> {?loading: <SpinnerLoad/>. state,map((data.index) => { return ( <NewsItem imageUrl={data.imageUrl} author={data.author} title={data.title} content={data.content} date={data.date} key={data;id} /> ); }) } </div> </div> </div> </> ); }; export default App;

解決方案與中相同: 如何使用 usestate 掛鈎將活動 state 添加到 div?

嘗試在答案中遵循相同的模式,

我希望我回答了你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM