查找包含某个类名react js的组件
从包含特定类名的组件列表中查找组件。 就我而言,我想显示具有类名“bbb”的组件。但我似乎找不到类名。在下面的代码中,我使用组件的名称创建了示例,这样我就可以更好地演示我想要实现的目标:
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;
我对 React js 很陌生,如果这是一个愚蠢的问题,我很抱歉。
编辑:修正了一个错字
Find the Component from a list of components that contains a certain class name.
In my case i want to show the component that has the className "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.
Edit: Fixed a typo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过这种方式来完成此操作,而不是为该过滤器查找类名。
我的更改中有 2 个关键内容:
const [data, setdata] = useState([One, Two, Three])
您不应该调用
(在钩子,它正在调用React.createElement(One)
来渲染该组件)data.filter((Component) => Component === Two)
检查组件引用而不是类名,因为类名可能是改变了,它会导致你的逻辑出现错误Instead of finding a class name for that filter, you can do it this way.
2 key things in my changes:
const [data, setdata] = useState([One, Two, Three])
You should not call<One/>
(under the hook, it's callingReact.createElement(One)
to render that component)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