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>
);
}
本质上,这是在将状态向上移动到父组件。这符合反应状态方法,如果您有一个状态需要在按钮之间进行协调,那么您应该将该状态向上移动到负责呈现按钮的组件。
添加回答
举报