在 React v18中,可以使用React.Children.toArray()方法将div的children转换为数组,然后使用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的children作为参数,并使用React.Children.toArray()将其转换为数组。然后,Array.find()方法用于查找具有aria-selected属性为true的子元素。在这个例子中,第二个ChildComponent具有aria-selected={true}属性,所以它将被返回。

请注意,aria-selected属性的值应该是布尔值,而不是字符串。在上面的示例中,我们使用了布尔值true和false

react v18 如何在 div的 children 中查找 aria-selected= true的

原文地址: https://www.cveoy.top/t/topic/iDgL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录