我正在尝试使用 setState 来更改我的布局。但为了让我的 React 应用程序正常工作,我需要 app.js 中的状态。因此不同的孩子可以访问它并根据需要进行编辑。但我得到的 Setstate 不是一个函数。这是为什么?我该如何解决它?
app.js
function App() {
const [isOpen, setIsOpen] = useState(false);
return (
<>
<Main />
<Card setIsOpen={setIsOpen} isOpen={isOpen} />
</>
);
}
export default App;
cards.js 组件是 app.js 的子组件
import React, { useState } from "react";
const Card = (setIsOpen, isOpen) => {
return (
<section className="cards">
<CloseBtn setIsOpen={setIsOpen} isOpen={isOpen} />
<div className="cards-content webdesign-content">
<WebIntro />
<SkillSection />
<Seo />
</div>
</section>
);
};
export default Card;
card.js 的 closebtn 子组件
import React, { useState } from "react";
const CloseBtn = (setIsOpen, isOpen) => {
return (
<>
<button
onClick={() => {
console.log(!isOpen);
setIsOpen(!isOpen); //==>Not WORKING
}}
className={buttonClassArr}
>
<i>Close</i>
</button>
</>
);
};
export default CloseBtn;
我已经尝试了console.log,但没有得到有用的结果。
这不是你传递道具的方式。您需要接收 props 对象并从中解构所需的 props。
// destruct the props inside curly braces
const Card = ({ setIsOpen, isOpen }) => {
return (
<section className="cards">
<CloseBtn setIsOpen={setIsOpen} isOpen={isOpen} />
</section>
);
};
// destruct the props inside curly braces
const CloseBtn = ({ setIsOpen, isOpen }) => {
return (
<button
onClick={() => {
console.log(!isOpen);
setIsOpen(!isOpen); // This should work now
}}
className={buttonClassArr}
>
<i>Close</i>
</button>
);
};