大佬教程收集整理的这篇文章主要介绍了将 useState Hook 传递给 React 上的另一个函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 useState 钩子中传递一个布尔值,该钩子在两个函数之间单击时打开和关闭模态。但是,我不断收到此错误消息:CAnnot destructure property 'setopenModal' of 'props' as it is undefined.
import React,{ useState,useEffect } from "react";
import * as Materials from "../components/Materials"; // <- Material.Js
const Main = () => {
const [openModal,setopenModal] = useState(false); //<- Opens (true) and Closes (false) Modal
const { MaterialContainer } = Materials.Materialtable(); // <-Calling Function Under Materialtable
return (
<MaterialContainer
openModal={openModal}
setopenModal={setopenModal}
/>
// This is how I am passing in Open/Close useState.
}
@H_666_2@material.Js
export const Materialtable = (props) => {
const { openModal,setopenModal } = props; // <- Pointed in Error message.
const openMaterialModal = (item) => {
console.log("button Clicked");
setopenModal(true); // <- Where I am passing in a true statement.
};
const MaterialContainer = () => (
<>
<table>stuff</table>
</>
);
return {
MaterialContainer
}
}
提前致谢。
从 React 的角度来看,@H_558_3@materialTable 组件的格式完全错误,尽管它是有效的 JavaScript。它只是一个普通的函数,它定义了几个常量,然后什么都不返回。 (好吧,在最初的问题中它什么都不返回。现在它返回一个对象。)
当你调用那个函数时,你确实没有传递任何东西给它:
const { MaterialContainer } = Materials.MaterialTable();
所以 props
将是 undefined
。
使 @H_558_3@materialTable 本身成为 React 组件:
export const MaterialTable = (props) => {
// destructure the props passed to the component
const { openModal,setOpenModal } = props;
// a function I assume you plan to use in the JSX below later?
const openMaterialModal = (item) => {
console.log("Button Clicked");
setOpenModal(true);
};
// the rendering of the component
return (
<>
<Table>stuff</Table>
</>
);
}
然后只需导入并使用该组件,而无需尝试从中解构任何内容或手动调用它:
import React,{ useState,useEffect } from "react";
// import the component
import { MaterialTable } from "../components/Materials";
const Main = () => {
// use the state hook
const [openModal,setOpenModal] = useState(false);
// render the component,passing props
return (
<MaterialTable
openModal={openModal}
setOpenModal={setOpenModal}
/>
);
}
以上是大佬教程为你收集整理的将 useState Hook 传递给 React 上的另一个函数全部内容,希望文章能够帮你解决将 useState Hook 传递给 React 上的另一个函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。