我對 React 比較陌生,正在嘗試為onclick事件設定子組件(SportTile)內的物件狀態。我很樂意通過使用單獨的useState()掛鉤來更新單個變數的狀態,但是,當您有很多變數時,這是一項繁瑣的任務。所以我使用了一個名為 : isClicked的物件 ,它存盤了各種運動的布林值,無論它們是否被用戶選擇。
我正在尋找的功能是,每當一個SportTile被點擊時,它的isClicked["sportname"]值被設定為 true,其余的被設定為 false。一次只能是一項運動。在控制臺記錄時isClicked
onclick()函式中的物件,我得到了所需的值,但它們沒有在父組件的(預訂)h1標簽中更新
import React from 'react';
import SportTile from '../SportTile';
import './booking.css';
import { useState } from 'react';
import SportsSoccerRoundedIcon from '@mui/icons-material/SportsSoccerRounded';
import SportsBasketballRoundedIcon from '@mui/icons-material/SportsBasketballRounded';
import SportsVolleyballIcon from '@mui/icons-material/SportsVolleyball';
import SportsTennisIcon from '@mui/icons-material/SportsTennis';
const Booking = () => {
const [isClicked, setIsClicked] = useState({
Football: false,
Basketball: false,
Volleyball: false,
Tennis: false,
});
return (
<div className='booking'>
<div className='booking__body'>
<div className='booking__left'>
<h1>SELECT SPORT</h1>
<SportTile
sportname={'Football'}
icon={<SportsSoccerRoundedIcon />}
clicked={setIsClicked}
isClicked={isClicked}
// test={setTestclicked}
// istestClicked={istestClicked}
/>
<SportTile
sportname={'Basketball'}
icon={<SportsBasketballRoundedIcon />}
clicked={setIsClicked}
isClicked={isClicked}
/>
<SportTile
sportname={'Volleyball'}
icon={<SportsVolleyballIcon />}
clicked={setIsClicked}
isClicked={isClicked}
/>
<SportTile
sportname={'Tennis'}
icon={<SportsTennisIcon />}
clicked={setIsClicked}
isClicked={isClicked}
/>
<h1>Football : {isClicked.Football.toString()} </h1>
<h1>Basketball : {isClicked.Basketball.toString()} </h1>
<h1>Volleyball : {isClicked.Volleyball.toString()} </h1>
<h1>Tennis : {isClicked.Tennis.toString()} </h1>
</div>
<div className='booking__right'>Right Side</div>
</div>
</div>
);
};
export default Booking;
import { Button } from '@mui/material';
import React from 'react';
import './sportTile.css';
const SportTile = ({
sportname,
icon,
clicked,
isClicked,
}) => {
function onclick() {
Object.keys(isClicked).map((key) => {
if (key == sportname) {
isClicked[key] = true;
} else {
isClicked[key] = false;
}
});
clicked(isClicked);
console.log(isClicked);
}
return (
<Button className='sportname__button' onClick={onclick}>
<div className='sportname__buttonColumn'>
{icon}
{sportname}
</div>
</Button>
);
};
export default SportTile;
也許我錯過了顯而易見的事情,但會感謝任何能指出我正確方向的人
uj5u.com熱心網友回復:
你永遠不應該傳遞原始的 setState 方法。在 Booking 組件中創建一個新方法:
const setIsClickedWrapper = (sportKey) = {
setIsClicked((isClicked) => Object.keys(isClicked).map((key) => sportKey === key)
}
在 SportTile 組件中只需呼叫:
const onclick = () => { setIsClickedWrapper(sportname) }
但我認為如果 isClicked 只是當前點擊的運動鍵的字串,那么它就足夠了:
const setIsClickedWrapper = (sportKey) = {
setIsClicked(sportKey)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/403387.html
標籤:
