首页 > 解决方案 > React:如何根据“If”语句启用 Button

问题描述

我的论坛页面上有一个按钮,除非您以 MongoDB 中定义的管理员身份登录,否则我希望禁用该按钮。(在 Mongo 中,我有一个角色文档,对于特定用户显示为“管理员”)

将在下面提供一些代码:

constructor(props) {
    super(props);
    this.state = {
      questions: [], // used to store questions from API call
      answers: [], // used to store all answers stored in database
      filteredAnswers: [], // used to store the filtered answers for a given question
      displayAnswers: false, // used to display the answer modal or not
      disabled: true,
      role: null,
    };
  }

handleClickPostAnswer(questionID, questionText) {
    const answerInput = window.prompt(`Please enter your answer to Question ${questionID}: ${questionText}`, 'Enter answer here');
    if (answerInput === null) {
      console.log('No answer posted');
      return;
    }

    else if (this.state.role == 'admin') {
      console.log('User is an Admin');
      this.setState({
        disabled: false,
      })
    }
    
    // ADD ACTUAL USERNAME HERE
    this.postAnswer(questionID, answerInput, 'John');
    console.log(`Posted answer: ${answerInput}`);
  }

componentDidMount() {
    axios.get('/getquestions')
        .then((response) => {
          console.log(response.data);
          this.setState({questions: response.data});
        });
  }

<tbody>
            {/* within the table, take array  */}
            {this.state.questions.map((question) => {
              return (
                <tr key = {question._id}>
                  <td>{question._id}</td>
                  <td>{question.questionText}</td>
                  <td>{question.username}</td>
                  <td>{question.labels}</td>
                  <td><Button disabled={this.state.disabled} onClick={() => this.handleClickPostAnswer(question._id, question.questionText)}>Answer</Button></td>
                  <td><Button onClick={() => this.handleClickReadAnswers(question._id)}>Display</Button></td>
                </tr>
              );
            })}
          </tbody>

目前,即使我以在 Mongo 中附加了“admin”字段的用户身份登录,该按钮似乎一直被禁用。可能缺少一些简单的东西,但不确定为什么这不起作用。

它在 MongoDB 中的外观

谢谢!

标签: reactjsmongodbbutton

解决方案


看起来你从来没有在状态中设置角色,下面的代码曾经记录过“'用户是管理员'”似乎没有。

else if (this.state.role == 'admin') {
      console.log('User is an Admin');
      this.setState({
        disabled: false,
      })
    }

在状态中设置角色,它应该有帮助


推荐阅读