reactjs - 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”字段的用户身份登录,该按钮似乎一直被禁用。可能缺少一些简单的东西,但不确定为什么这不起作用。
谢谢!
解决方案
看起来你从来没有在状态中设置角色,下面的代码曾经记录过“'用户是管理员'”似乎没有。
else if (this.state.role == 'admin') {
console.log('User is an Admin');
this.setState({
disabled: false,
})
}
在状态中设置角色,它应该有帮助
推荐阅读
- javascript - 部署的数据库没有连接
- spring-mvc - 如何在运行时以编程方式获取 @ComponentScan 的 basePackages?
- python - 在 Python Pandas 中,不能在日期时间列之后添加新列
- asp.net-mvc - FineUploader 无法发布
- ios - 调用 tableview reloadData 后自定义单元格不会重新加载 UI
- r - 累积分布的变化点检测
- javascript - Sweetalert 确认表单提交失败
- firebase - 使用 firebase 功能配置 firebase 实时数据库
- nlp - NLP:按意图分句
- javascript - Angular验证身份号码的前6位