React v18: 在 div 子元素中查找 aria-selected=true 的内容
在 React v18 中,可以使用 'React.Children.toArray()' 方法将 'div' 的子元素转换为数组,然后使用 'Array.find()' 方法查找具有 'aria-selected' 属性为 'true' 的元素。
以下是一个示例代码:
import React from 'react';
function App() {
const findSelectedChild = (children) => {
const childrenArray = React.Children.toArray(children);
return childrenArray.find((child) => child.props['aria-selected'] === true);
};
return (
<div>
<ChildComponent aria-selected={false} />
<ChildComponent aria-selected={true} />
<ChildComponent aria-selected={false} />
</div>
);
}
function ChildComponent({ ariaSelected }) {
return <div aria-selected={ariaSelected}>Child Component</div>;
}
export default App;
在上面的示例中,'findSelectedChild' 函数接受 'div' 的子元素作为参数,并使用 'React.Children.toArray()' 将其转换为数组。然后,'Array.find()' 方法用于查找具有 'aria-selected' 属性为 'true' 的子元素。在这个例子中,第二个 'ChildComponent' 具有 'aria-selected={true}' 属性,所以它将被返回。
请注意,'aria-selected' 属性的值应该是布尔值,而不是字符串。在上面的示例中,我们使用了布尔值 'true' 和 'false'。
原文地址: https://www.cveoy.top/t/topic/qjVj 著作权归作者所有。请勿转载和采集!