我已经使用 useState hook 创建了状态,并且我尝试将 setState 函数作为道具发送给子组件,但是当我在按钮“onclick”中使用该函数时,它给了我一个错误: setSelectedTag 不是 onClick 的函数
page.tsx:
export default function Home(post: Post) {
//creating state
const [selectedTag, setSelectedTag] = useState("All");
//passing the state as props. in a child component
<BlogFilter
selectedTag={selectedTag}
setSelectedTag={setSelectedTag}
tags={arrString}
></BlogFilter>
blogfilter.tsx:
import React from "react";
export default function BlogFilter(
tags: any,
selectedTag: any,
setSelectedTag: any
) {
if (tags?.length === 0) {
return null;
}
//spliting the string , also converting the string into an array.
const duplicateArr = tags?.tags.split(",");
// console.log(duplicateArr);
//removing duplicates from array
const withoutDuplicates = duplicateArr?.filter(
(value: any, index: any, array: string | any[]) =>
array.indexOf(value) === index
);
tags = withoutDuplicates?.map((t: any) => t.trim());
// console.log(tags);
return tags?.map((tag: any) => (
<button
key={tag}
className={`ml-2 rounded-full hover:bg-indigo-600
${selectedTag === tag ? "active:bg-indigo-700" : " bg-indigo-500"}
focus:outline-none focus:ring focus:ring-indigo-300
px-3 text-[11px] font-light text-white`}
** onClick={() => {
setSelectedTag(tag);
**
console.log(typeof tag);
}}
>
# {tag}
</button>
));
}
在 page.tsx 文件中,当您将 props 发送到 BlogFilter 组件时:
<BlogFilter
selectedTag={selectedTag}
setSelectedTag={setSelectedTag}
tags={arrString}
/>
代替:
export default function BlogFilter(tags, setSelectedTag, selectedTag) {
// ...
}
您应该使用:
export default function BlogFilter({ tags, setSelectedTag, selectedTag }) {
// ...
}