Así que estoy tratando de implementar un sistema de comentarios con React. (No interactivo, solo para renderizar datos). Tengo problemas para mostrar las respuestas de cada comentario en la vista.
comments.js (exporta todos los datos de los comentarios)
const comments = [ { ....metadata, // this is where all the metadata for the comment goes, such as the content replies: [ { ...metadata, replies: [ // ...zero or more replies, of the same shape as comments[0] ] } ] }, // ...other comments, of the same shape as comments[0] export default comments comment.jsx (el componente funcional al que se pasa cada elemento de la matriz de comments anterior (y las replies de cada elemento):
const Comment = props => ( <div> <div> {/* this is where all the comment's metadata will be rendered into */} </div> <div>{props.replies}</div> </div> ) export default commentApp.jsx (lo que terminará siendo renderizado en el DOM)
import comments from "./comments.js" import Comment from "./comment.jsx" const App = () => ( {comments.map(comment => ( <Comment {...comment.metadata, replies:{comment.replies.map(reply => ( <Comment {...reply.metadata} /> ))} } /> )) } ) El problema con mi enfoque es que las replies que están enterradas a más de 1 nivel de profundidad desde el comentario superior (es decir, replies de replies ), no se procesarán en el DOM.
¿Alguien puede proporcionar una forma de representar todas las respuestas, hasta la respuesta más interna?
¡Gracias!
Por favor revisa lo siguiente
Hay un componente de comentario que se repite recursivamente,
import React, { useState } from 'react'; const Comment = ({ msg }) => { return <div>{msg}</div>; }; export default function App() { const [comments] = useState([ { msg: 'Lorem ipsum 1', replies: [{ msg: 'Lorem 1.1', replies:[{msg: 'Lorem 1.1.1'}] }] }, { msg: 'Lorem ipsum 2' }, { msg: 'Lorem ipsum 3', replies: [{ msg: 'Lorem 3.1' }] }, ]); const renderEl = (commentsData) => { return ( <> { commentsData.map((r, k) => ( <div style={{ marginLeft: '3%' }} key={k}> <Comment msg={r.msg} /> {r.replies && r.replies.length > 0 ? renderEl(r.replies, 0) : null} </div> )) } </> ); }; return renderEl(comments); }Puede usar la recursividad para generar anidamiento de n niveles.
const createComment = (comments) => ( <> {comments.map((comment) => ( <div key={comment.id}> <div>{props.text}</div> {comment.replies && comment.replies.map(rp => (createComment(rp.replies))} </div> ))} </> ); export default function App() { const comments = [{ id: 1, text: "This is a comment", replies: [ { id: 2, text: "This is a reply", replies: [ { id: 3, text: "This is a reply", replies: [], }, ], }, ], }]; return ( <div className="App"> {createComment(comments)} </div> ) }