Tengo este código en particular que muestra una lista de preguntas y botones para cada uno de ellos. Cuando hago clic en el botón, se mostrará la respuesta específica a la pregunta. Mi problema es que tengo un montón de preguntas y cuando hago clic en el botón, se mostrarán todas las respuestas en lugar de la respuesta específica a esa pregunta.
Aquí está el código
class App extends React.Component { constructor(){ super() this.state = { answer: [], isHidden: true } this.toggleHidden = this.toggleHidden.bind(this) } componentWillMount(){ fetch('http://www.reddit.com/r/DrunkOrAKid/hot.json?sort=hot') .then(res => res.json()) .then( (data) => { const answer = data.data.children.map(obj => obj.data); this.setState({answer}); }) } toggleHidden(){ this.setState({isHidden: !this.state.isHidden}) } render(){ const answer = this.state.answer.slice(2) return <div> <h1>Drunk or Kid</h1> {answer.map(answer => <div key={answer.id}> <p className="title">{answer.title}</p> <button onClick={this.toggleHidden}>Answer</button> {!this.state.isHidden && <Show>{answer.selftext}</Show>} </div> )} </div> } } const Show = (props) => <p className="answer">{props.children}</p>Y aquí está el enlace al codepen
Aquí hay un Codepen basado en mi sugerencia:
Los conceptos básicos del componente hijo serían:
class Question extends React.Component { // Set initial state of isHidden to false constructor() { super(); this.state = { isHidden: false } } // Toggle the visibility toggleHidden() { this.setState({ isHidden: !this.state.isHidden }); } // Render the component render() { const { answer } = this.props; return ( <div key={answer.id}> <p className="title">{answer.title}</p> <button onClick={ () => this.toggleHidden() }>Answer</button> {this.state.isHidden && <Show>{answer.selftext}</Show>} </div> ); } }Luego, lo asignaría dentro del componente principal como:
answer.map(answer => <Question answer={answer} key={answer.id} /> )Otra opción es agregar un estado que guarde la identificación de la respuesta abierta y luego verificar si la respuesta específica está en ese estado o no.
veamos en acción
class SomeComponent extends React.Component { constructor(props){ super(props) this.state = { opened: [] } this.toggleShowHide = this.toggleShowHide.bind(this) } toggleShowHide(e){ const id = parseInt(e.currentTarget.dataset.id) if (this.state.opened.indexOf(id) != -1){ // remove from array this.setState({opened: this.state.opened.filter(o => o !== id)}) } else { this.setState({opened: [...this.state.opened, id]}) } } render(){ return <ul> { this.state.answers.map(ans => ( <li key={ans.id} data-id={ans.id}> question <button onClick={this.toggleShowHide}>show answer</button> <span style={{ display: this.state.opened.indexOf(ans.id) !== -1 ? 'block' : 'none' }}>answer</span> </li> ))} </ul> } }Aquí hay un video en acción https://www.youtube.com/watch?v=GJsPEsckB4w