react 如何获取key
获取 React 中元素的 key
在 React 中,key 是用于优化列表渲染的特殊属性,通常不建议在组件内部直接访问。但若需要获取 key,可以通过以下方法实现:
通过 props 传递 key
将 key 作为普通属性传递给子组件,然后在子组件中通过 props 访问。
// 父组件
const ParentComponent = () => {
const items = [{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }];
return (
<div>
{items.map(item => (
<ChildComponent key={item.id} itemKey={item.id} name={item.name} />
))}
</div>
);
};
// 子组件
const ChildComponent = (props) => {
console.log(props.itemKey); // 输出 key 值
return <div>{props.name}</div>;
};
通过 ref 获取 key
使用 React.forwardRef 和 useRef 结合,获取 DOM 节点的 key 属性。
// 子组件(通过 forwardRef 暴露 ref)
const ChildComponent = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.name}</div>;
});
// 父组件
const ParentComponent = () => {
const items = [{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }];
const refs = items.map(() => React.useRef(null));
React.useEffect(() => {
refs.forEach((ref, index) => {
if (ref.current) {
console.log(ref.current.parentElement.getAttribute("key")); // 间接获取 key
}
});
}, []);
return (
<div>
{items.map((item, index) => (
<ChildComponent key={item.id} ref={refs[index]} name={item.name} />
))}
</div>
);
};
注意事项
- 避免直接依赖 key:React 的
key主要用于内部优化,直接操作可能导致意外行为。 - 替代方案:建议通过显式传递
id或唯一标识符替代直接访问key。 - 动态列表:确保
key是稳定且唯一的,避免使用数组索引。
使用 Context 传递 key
若需要在深层嵌套组件中访问 key,可通过 Context 传递。
const KeyContext = React.createContext();
// 父组件
const ParentComponent = () => {
const items = [{ id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }];
return (
<div>
{items.map(item => (
<KeyContext.Provider value={item.id} key={item.id}>
<ChildComponent name={item.name} />
</KeyContext.Provider>
))}
</div>
);
};
// 子组件
const ChildComponent = (props) => {
const key = React.useContext(KeyContext);
console.log(key); // 输出 key 值
return <div>{props.name}</div>;
};






