我从一个简单的 JSX 元素数组开始:
const jsxArray = dataItems.map(item => (
<div>
<Header>{item.title}</Header>
<Paragraph>{item.body}</Paragraph>
<Paragraph customAttribute={item.isActive} >{item.tags}</Paragraph>
</div>
))
在渲染内部,或者更确切地说返回,因为我现在对所有内容都使用函数组件,我想过滤 isActive
属性标记为 true
的 JSX 元素。
return (
{jsxArray
.filter(jsxElement => // want to filter in JSX elements
// that are true for customAttribute keyed to `item.isActive`)
}
)
有什么办法吗?
如果没有一个好的方法,我愿意采取变通办法。
我可以在前面的步骤中简单地过滤数组。但这会导致一些额外的代码重复,因为我在其他地方仍然需要未过滤的 JSX 元素数组。
最佳答案
渲染列表后,您不会对其进行过滤。那时它只是一棵节点树,不再有太多意义。
相反,您首先过滤项目,然后然后仅渲染符合您条件的项目。
const jsxArray = dataItems.filter(item => item.isActive).map(item => (
<div>
<h3>{item.title}</p>
<p>{item.body}</p>
<p customAttribute={item.isActive} >{item.tags}</p>
</div>
))
<小时/>
It is possible for me to simply filter the array at an earlier step. It would result in some extra code duplication though, since I would still need the array of unfiltered JSX elements elsewhere.
不一定。当我自己处理这样的过滤时,我创建了两个变量,一个用于原始的未过滤列表,一个用于过滤后的项目。然后无论您要渲染什么,都可以根据需要选择其中之一。
const [items, setItems] = useState([])
const filteredItems = items.filter(item => item.isActive)
return <>
<p>Total Items: ${items.length}</p>
<ItemList items={filteredItems} />
</>
关于javascript - React.js : How to filter JSX element array on custom attribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60497895/