我从一个简单的JSX元素数组开始:
const jsxArray = dataItems.map(item => (
<div>
<Header>{item.title}</Header>
<Paragraph>{item.body}</Paragraph>
<Paragraph customAttribute={item.isActive} >{item.tags}</Paragraph>
</div>
))
在render内部,或者更确切地说是返回,因为我现在对所有内容都使用功能组件,所以我想过滤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>
))
我可以在前面的步骤中简单地过滤数组。不过,这会导致一些额外的代码重复,因为我在其他地方仍然需要未过滤的JSX元素数组。
不一定。当我自己处理这样的过滤时,我创建了两个变量,一个用于原始的未过滤列表,另一个用于过滤项目。然后,无论渲染什么,都可以根据需要选择其中一个。
const [items, setItems] = useState([])
const filteredItems = items.filter(item => item.isActive)
return <>
<p>Total Items: ${items.length}</p>
<ItemList items={filteredItems} />
</>
与其访问jsx
元素属性(我认为这要么不可能,要么非常困难(,我建议您这样做:
-
保存箭头函数中项目的渲染器函数
const itemRenderer = item => ( <div> <Header>{item.title}</Header> <Paragraph>{item.body}</Paragraph> <Paragraph customAttribute={item.isActive} >{item.tags}</Paragraph> </div> )
-
将过滤功能保存在箭头功能中
const activeItems = item => item.isActive
-
使用它们来过滤和映射
const jsxArray = dataItems.filter(activeItems).map(itemRenderer)
-
使用它们只映射
const jsxArray = dataItems.filter(activeItems).map(itemRenderer)
希望这能有所帮助!
通常,您会先过滤纯数据,然后只为过滤后的元素呈现标记,如@Alex Wayne answer中所述。
如果您担心标记的重复,可以通过从中提取一个组件来解决:
const Item = ({title, body, isActive, tags}) => (
<div>
<Header>{title}</Header>
<Paragraph>{body}</Paragraph>
<Paragraph customAttribute={isActive}>{tags}</Paragraph>
</div>
);
为了呈现过滤后的列表,您可以执行以下操作:
{items.filter(item => item.isActive).map(item => <Item {...item} />)}
对于未过滤的列表:
{items.map(item => <Item {...item} />)}