let newRefObj = useRef({});
newRefObj.current = {};
//Object.keys(menuData) returns ['angus_burger', 'chicken_sandwiches', 'fish_veg', 'specials', 'salads', 'sides_bevs']
let menuDataArr = Object.keys(menuData).map(categoryID => {
menuData[categoryID]['eleRef'] = newRefObj.current[categoryID];
//^newRefObj.current[categoryID] returns undefined even though if I were to console.log(newRefObj.current),
the console shows it has keys with the html element
return menuData[categoryID];
})
<MenuCategory
key={uuid()}
header={category.header}
note={category.note}
menuItems={category.menuItems}
//category.categoryID returns one of the keys above (ie: category.categoryID = 'angus burger')
ref={el => newRefObj.current[category.categoryID] = el}
categoryID={category.categoryID}
/>
因此,我不确定运行上述代码的父组件呈现后发生了什么,我的ref对象(newRefObj.current)返回了一个带有键的对象,这些键全部返回html元素引用。但是,如果我要使用console.log(newRefObj.current.angus_burgers)或其他任何键,它将返回未定义的值。我是否不了解useRef对象?
对不起,如果我不清楚。只是觉得有点奇怪。
编辑:(整个组件)
export default function Menu(props){
let newRefObj = useRef({});
newRefObj.current = {};
let menuDataArr = Object.keys(menuData).map(categoryID => {
console.log(newRefObj.current.sides_bevs, categoryID)
menuData[categoryID]['eleRef'] = newRefObj.current[categoryID];
return menuData[categoryID];
})
let [currentCategory, setCurrentCategory] = useState('');
function executeScroll(ref){
window.scrollTo({left: 0, top: ref.current.offsetTop - 100, behavior: 'smooth'})
setCurrentCategory(ref.current.dataset.categoryid)
}
return (
<div className="Menu">
<div className="Menu-headerArea">
<p>Focused on every detail, <span className="Menu-brand">Charred</span> brings our backyard to <span>you</span></p>
</div>
<div className="Menu-headerArea Menu-headerArea--secondary">
<i className="fas fa-hamburger"></i>
<h3>The Menu</h3>
<MenuCategoryBtns
menuDataArr={menuDataArr}
executeScroll={executeScroll}
currentCategory={currentCategory}
/>
</div>
<div className="Menu-board">
{menuDataArr.map(category => (
<MenuCategory
key={uuid()}
header={category.header}
note={category.note}
menuItems={category.menuItems}
ref={el => newRefObj.current[category.categoryID] = el}
categoryID={category.categoryID}
/>
))}
</div>
</div>
)
}
答案 0 :(得分:0)
您的menuData[categoryID]['eleRef'] = newRefObj.current[categoryID];
总是会导致设置undefined
,因为在您运行它的那一刻,newRefObj.current
是空的(因为您在此之前明确地做了newRefObj.current = {};
您设置了menuDataArr
)