2 回答

TA貢獻1789條經驗 獲得超10個贊
你的代碼可能看起來像這樣來實現你正在尋找的東西:
function parentComponet() {
// vvv this was added vvv
const [pressedIndex, setPressedIndex] = useState(null);
// ... everything else
// vvv code was added here too compare to your original code vvv
tags.forEach((tag, index) => {
let saida = <PressedButton pressed={pressedIndex === index} onClick={() => {handleTag(tag); setPressedIndex(index)}}>{tag}</PressedButton>
}
然后在孩子身上:
function PressedButton({ children, pressed, ...rest }) {
// vvv this was removed vvv
// const [pressed, setPressed] = useState(false);
return (
<Container>
<Content
type="button" {...rest}
pressed={pressed}
onFocus={() => setPressed(!pressed)}
>
{children}
</Content>
</Container>
);
}
本質上,這是在將狀態向上移動到父組件。這符合反應狀態方法,如果您有一個狀態需要在按鈕之間進行協調,那么您應該將該狀態向上移動到負責呈現按鈕的組件。
添加回答
舉報