简体   繁体   English

找到包含某个 class 名称的组件 react js

[英]find a component that contains a certain class name react js

Find the Component from a list of components that contains a certain class name.从包含特定 class 名称的组件列表中查找组件。 In my case i want to show the component that has the className "bbb".在我的例子中,我想显示具有类名“bbb”的组件。 But I can't seem to find the className.但我似乎找不到类名。 In the code below i made my example with the Name of the component just so I can demonstrate better what i want to achieve:在下面的代码中,我用组件的名称做了我的例子,这样我就可以更好地展示我想要实现的目标:

import React, { useState, useEffect } from 'react';

const Test = () => {

  const One = () => {
    return (
      <h1 className='aaa' >one</h1>
    )
  }
  const Two = () => {
    return (
      <h1 className='bbb' >two</h1>
    )
  }
  const Three = () => {
    return (
      <h1 className='ccc' >Three</h1>
    )
  }

  const [data, setdata] = useState([<One />, <Two />, <Three />])

  return (
    <section>
      {data.filter(x => x.type.name === 'One').map(x => {
      // something like this line below. This doesn't work of course
      // {data.filter(x => x.classList.contains('bbb)).map(x => {
        return <div>{x}</div>
      })}
    </section>
  )
};

export default Test;

I am really new to React js so sorry if this is a stupid question.我真的是 React js 的新手,如果这是一个愚蠢的问题,我很抱歉。

Edit: Fixed a typo编辑:修正了一个错字

Instead of finding a class name for that filter, you can do it this way.您可以这样做,而不是为该过滤器查找 class 名称。

2 key things in my changes:我更改中的 2 个关键事项:

const [data, setdata] = useState([One, Two, Three]) You should not call <One/> (under the hook, it's calling React.createElement(One) to render that component) const [data, setdata] = useState([One, Two, Three])你不应该调用<One/> (在钩子下,它调用React.createElement(One)来渲染那个组件)

data.filter((Component) => Component === Two) Check the component reference instead of class name, because class name may be changed and it will cause a bug in your logic data.filter((Component) => Component === Two)检查组件引用而不是 class 名称,因为 class 名称可能会更改,这会导致您的逻辑出现错误

import React, { useState, useEffect } from 'react'

const Test = () => {
  const One = () => {
    return <h1 className="aaa">one</h1>
  }
  const Two = () => {
    return <h1 className="bbb">two</h1>
  }
  const Three = () => {
    return <h1 className="ccc">Three</h1>
  }

  const [data, setdata] = useState([One, Two, Three])

  return (
    <section>
      {data
        .filter((Component) => Component === Two)
        .map((Component) => {
          return (
            <div>
              <Component />
            </div>
          )
        })}
    </section>
  )
}

export default Test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM