计算递归反应组件中 Children 的数量
Count number of Children in recursive react component
我正在开发一个评论系统并使用递归方法来显示 parent 和 child 评论。当我删除 child 时,我想更新其 parent.
的 child 评论数
//json 数据
数据 = [{
姓名:'Parent1',
child评论:[{
姓名:'Child1',
文字:'child comment1'
},
{
姓名:'Child2',
文字:'child comment2'
}]
},{
姓名:'Parent2',
child评论:[{
姓名:'Child1',
文字:'child comment1'
},
{
姓名:'Child2',
文字:'child comment2'
}]
}]
const Comment = ({ item }) => {
const childComment = item
//delete child element and update the parent count
const deleteChildComment =(item) => {
}
return childComment && (
<>
{name}
Children count : {childComments.length}
<Button
className={styles.replies}
onClick={() => {
setNewCommentAdded(false)
deleteChildComment(childComment)
}}
> Delete This comment </Button>
{childComments && items.map((item) => (
<Comment item={item} />
))}
</>
)
}
数 children 不是个好主意,会让事情变得太复杂。
只需使用您用于生成评论组件的数据即可。
作为一项规则,始终使用 UI 表示数据。不要尝试从您的 UI 布局中获取数据。
例如
commentList.map((comment) => (<Comment childCount={comment.children.length}));
我正在开发一个评论系统并使用递归方法来显示 parent 和 child 评论。当我删除 child 时,我想更新其 parent.
的 child 评论数//json 数据 数据 = [{ 姓名:'Parent1', child评论:[{ 姓名:'Child1', 文字:'child comment1' }, { 姓名:'Child2', 文字:'child comment2' }] },{ 姓名:'Parent2', child评论:[{ 姓名:'Child1', 文字:'child comment1' }, { 姓名:'Child2', 文字:'child comment2' }] }]
const Comment = ({ item }) => {
const childComment = item
//delete child element and update the parent count
const deleteChildComment =(item) => {
}
return childComment && (
<>
{name}
Children count : {childComments.length}
<Button
className={styles.replies}
onClick={() => {
setNewCommentAdded(false)
deleteChildComment(childComment)
}}
> Delete This comment </Button>
{childComments && items.map((item) => (
<Comment item={item} />
))}
</>
)
}
数 children 不是个好主意,会让事情变得太复杂。 只需使用您用于生成评论组件的数据即可。
作为一项规则,始终使用 UI 表示数据。不要尝试从您的 UI 布局中获取数据。
例如
commentList.map((comment) => (<Comment childCount={comment.children.length}));