这里是新手问题,是钩子和React的新手,我希望能够单击Nav组件中的过滤器按钮,并仅在App组件中显示该div类别:
https://codesandbox.io/s/filter-menu-react-cbwhk
最有效的方法是什么?
答案 0 :(得分:1)
使用箭头过滤器功能Array.prototype.filter()解决方案:
import React, { useState } from "react";
import "./styles.css";
import Nav from "./Nav";
const styles = {
padding: "10px",
margin: "5px",
background: "gold",
width: "100px",
height: "100px",
display: "inline-block"
};
export default function App() {
const data = ["dog", "cat", "lizard", "dog", "cat", "dog", "lizard", "dog"];
const [filter, setFilter] = useState("all");
//what I'm having trouble with:
// function filterTags(filter){data.map(x => {
// if(x.dataset.tags.includes("filter")){
// return (
// <div data-tags={x} style={styles}>
// {x}
// </div>
// );
// })
// }
// };
console.log(filter)
return (
<div className="App">
<Nav filter={filter} setFilter={setFilter} />
{/* {filterTags(filter)} */}
{/* only show the filtered divs */}
{data.filter(_ => filter === _).map((x,i) => {
return (
<div key={i} data-tags={x} style={styles}>
{x}
</div>
);
})}
</div>
);
}
答案 1 :(得分:1)
您也可以这样尝试...只需检查地图功能中的条件即可。 https://lcizy.csb.app/
export default function App() {
const data = ["dog", "cat", "lizard", "dog", "cat", "dog", "lizard", "dog"];
const [filter, setFilter] = useState("all");
function filterTags(val) {
setFilter(val);
}
console.log(data);
return (
<div className="App">
<Nav filter={filter} setFilter={filterTags} />
{data.map((x, i) =>
filter === x || filter === "all" ? (
<div key={i} data-tags={x} style={styles}>
{x}
</div>
) : null
)}
</div>
);
}