Yes, it is possible to check the type of children components and filter specific components. One way to do this is by using the React.Children utility.

Here's an example:

function MyComponent({ children }) {
  const filteredChildren = React.Children.toArray(children).filter(child => {
    return child.type === MyChildComponent;
  });

  return (
    <div>
      {filteredChildren}
    </div>
  );
}

function MyChildComponent() {
  return <div>Child component</div>;
}

function App() {
  return (
    <MyComponent>
      <div>Not a child component</div>
      <MyChildComponent />
      <MyChildComponent />
      <div>Another non-child component</div>
    </MyComponent>
  );
}

In this example, MyComponent receives children as props, and uses React.Children.toArray to convert them into an array of React elements. It then filters this array to only include elements of type MyChildComponent. The filtered array is then rendered within a div.

Note that child.type is used to compare the type of the child component to MyChildComponent. This works even if the code is minified, as long as the displayName or name property of the component is not modified

Is it possible to check children components type and filter specific components How to do it Note the code will be minified

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

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