1

我正在制作具有可折叠回复的嵌套评论。为此,我只需按照收到它们的顺序将所有评论呈现在平面列表中,然后根据每个项目的级别属性在左侧添加一个边距。传入的评论数据如下。

{
    id: "1a",
    parent: "a",
    author: "joemorgan",
    body: "Such an amazing car, had seen this one in Paris earlier!",
    level: 0,
    replies: ["4w", "2f"]
},
{
    id: "4w",
    parent: "1a",
    author: "jason",
    body: "Truly a beast",
    level: 1,
    replies: []
},
{
    id: "2f",
    parent: "1a",
    author: "katparis",
    body: "Rightly said",
    level: 1,
    replies: []
},

然后我使用以下平面列表呈现这些评论

             <FlatList
                    data={SAMPLE_COMMENTS}
                    keyExtractor={item=>item.id.toString()}
                    renderItem={Comment body={item.body} level={item.level} commentId={item.id} commentChildren={item.replies} />}
/>

最后,我将实际的评论组件包装在一个 Collapsible(react-native-collapsible 包)中。这样我可以通过点击它来折叠特定的评论。'collapsed' 属性是使用 isCollapsed 状态设置的。

   const [isCollapsed, setIsCollapsed] = useState(false);


   <Collapsible collapsed={isCollapsed}>
    
        <TouchableWithoutFeedback onPress={()=> setIsCollapsed(true) }>
            <View style={styles.container}>
               

            </View>
        </TouchableWithoutFeedback>

    </Collapsible>

使用上面的代码,我可以通过点击来折叠每个单独的评论。

问题是我不想折叠我正在按下的评论。我想折叠它的孩子,为此我真的很想知道如何在不影响父评论的情况下为父评论的孩子操纵 isCollapsed 状态。由于每条评论都有一个唯一的 id,我相信也许可以使用它来完成?每个评论的孩子也是一个属性,所以也许这也有帮助。

任何线索都会非常有帮助。谢谢

4

1 回答 1

0

You apparently do have a property commentChildren, but I can't see what it contains. Can't you use that property to collapse all comment children ?

Anyway, if not:
The logic to decide which item-components should be collapsed needs to be outside of the item-components, and the item-components would just have their own state and a callback to inform that controller logic, like "I was clicked, my ID is xyz". The controller would then know what to do.

Like:

const childsOfComment = findChildCommentsRecursively( allComments, clickedComment );
...
<Comment
    commentId={ item.id }
    isCollapsed={ childsOfComment.includes( item.id ) }
/>

Maybe even better would be to maintain the whole list including the information about what to collapse in the state, and have the render function just render that state.

{
    id: "1a",
    collapsed: true,  // <-- store collapsed info in state
    parent: "a",
    ...
},

This might need some refactoring though, and might be more complicated, depending on if you need to maintain the original list as well.

于 2021-12-05T11:01:40.307 回答