reactjs - 自定义 Hook 和级联下拉菜单
问题描述
我是新手,我正在边做边学。现在我正在使用自定义 Hook 在组件之间共享逻辑。
这是自定义 Hook 内部的逻辑
const useDropDownLogic = () => {
const { menu } = useContext(MenuContext)
const brand = [...new Set(menu.map(i => i.brand))]
const [category, setCategory] = useState([])
const brandChange = (e) => {
const { type, textContent } = e.target
setCategory([...new Set(menu.filter(i => i.[type] == textContent).map(i => i.category))])}
return {
brandChange,
brand,
category
}
}
export default useDropDownLogic;
这是使用自定义 Hook 的第一个组件
const DropDownBrand = () => {
const {brandChange, brand} = useDropDownLogic();
const dropdownRef = useRef(null);
const [isActive, setIsActive] = useDetectOutsideClick(dropdownRef, false);
const onClick = () => setIsActive(!isActive)
return (
<div id="dropdownbrand">
<div className="menu-container menu-brand">
<label className = 'nav-label'>Select a Brand</label>
<button onClick={onClick} className="menu-trigger brand-btn">
<i className="fas fa-chevron-down fa-2x drop-arrow"></i>
</button>
<nav
ref={dropdownRef}
className={`drop-menu ${isActive ? "active" : "inactive"}`}
>
<ul>
{brand.map((i) => (<li key={nanoid()} type = 'brand' value={i} onClick = {(e) => brandChange(e)}>{i}</li>))}
</ul>
</nav>
</div>
</div>
);
};
导出默认 DropDownBrand;
这是第二个
const DropDownCategory = () => {
const { category } = useDropDownLogic()
const dropdownRef = useRef(null);
const [isActive, setIsActive] = useDetectOutsideClick(dropdownRef, false);
const onClick = () => setIsActive(!isActive)
console.log(category);
return (
<div id="dropcategory">
<div className="menu-container menu-brand">
<label className = 'nav-label'>Select a Brand</label>
<button onClick={onClick} className="menu-trigger brand-btn">
<i className="fas fa-chevron-down fa-2x drop-arrow"></i>
</button>
<nav
ref={dropdownRef}
className={`drop-menu ${isActive ? "active" : "inactive"}`}
>
<ul>
{category.map((i) => (<li key={nanoid()} type = 'category'>{i}</li>))}
</ul>
</nav>
</div>
</div>
);
};
export default DropDownCategory;
基本上我可以填充第一个下拉列表,但不能填充第二个。我不明白为什么类别状态没有更新到 DropDownCategory 组件中
任何提示我做错了什么?
提前谢谢了
解决方案
I see,
I'm changing the approach. Moving state to a parent component and passing down function to handle click event. Then on Parent I'll update the dstate and pass it as props down to the child. Nyhting to share yet but it will come
推荐阅读
- amazon-web-services - 通过代码在 Athena 中创建表会导致错误:不匹配的输入 'ROW' 期望 {
, '和'} - ruby-on-rails - 如何使用表单让 trix-rails 在 rails5.2 上工作
- python - 使用可选键创建有效负载
- php - 显示特定类别的帖子
- iis-10 - 更改时区 IIS10 日志
- python - python表达式的c ++返回类型不清楚
- c - 如何使用 gtk+-3.0 和 C 从图像中创建方形按钮?
- redux - react-router-redux vs connected-react-router for react v4
- r - R:POSIXct 转换失败,尽管设置了本地
- mysql - 在一个表中加入两个用逗号分隔的字符串 id 的表