如何将 table 中特定行的 id 传递给 reactjs 中的函数?

How to pass the id of a specific row in a table to a function in reactjs?

我已经通过 axios 获取了数据库的值,并将它们显示在 table 中。所以数据库包含问题和答案。单击 'Show Answer' 时,我需要显示该特定问题的答案并将按钮的文本更改为“隐藏答案”。

我曾尝试使用 this.state 和 this.setState 来更改值。但是 table 中的每一行都会发生变化。但我只需要更改已单击的特定行。

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';

class App extends Component {

constructor(props) {
super(props);
this.state = {
    questions: [],
    displayAnswer: false
    };
}
 componentDidMount(){
      axios.get('http://localhost:3000/api/question/')
      .then(response => {
        this.setState({ questions: response.data })
  })
  .catch(err => console.error(err))
 }
toggleAnswer(ques_id) {
//how do i change here for a particular row and not for the whole table
}

 render() {
return (
    <div>
        <h1>Questions</h1>
       <table>
            {
                 this.state.questions.map((questions) => (
                 <tr key={questions.id}>
                     <td>{questions.question}
                    //the question.answer goes here
                    </td>
                     <td> 
                 <button onClick={() => this.toggleAnswer(questions.id)}>{this.state.displayAnswer ? 'Hide Answer' : 'Show Answer'}</button></td>
                 </tr>
                 ))
            }
        </table>
    </div>
);
}
 }
 export default App;

您需要为每个问题维护 displayAnswer 属性。我会建议这样的事情,

  toggleAnswer(questionId) {
      const questions = this.state.questions.map(value=> value.id === questionId ? 
           {...value, displayAnswer : value.displayAnswer !== undefined ? !value.displayAnswer : true } : value);
      this.setState({questions})
}

然后在 this.state.displayAnswer ? 'Hide Answer' : 'Show Answer' 中使用 questions.displayAnswer 而不是 this.state.displayAnswer