我有这个子组件,它呈现一个“report bugg”按钮,当它被按下时应该显示 report bugg 表单。 例如:按下按钮 -> 状态更新为 report_toggle = true
如这段代码所示:
import React from 'react';
import ReportBox from './ReportBox';
class ReportBugButton extends React.Component {
constructor(){
super();
this.toggleReportBox = this.toggleReportBox.bind(this);
this.reportSubmit = this.reportSubmit.bind(this);
this.state = {
report_toggle: true
}
}
toggleReportBox(e){
e.preventDefault();
this.state.report_toggle ? this.state.report_toggle = false : this.state.report_toggle = true;
console.log("State ist: ", this.state.report_toggle);
}
reportSubmit(e){
e.preventDefault();
}
render() {
return(
<div>
<a href="#" onClick={this.toggleReportBox} className="report-button tooltip" title="Report a bug"><i className="fa fa-bug"></i></a>
{ this.state.report_toggle ? <ReportBox toggleReport={this.toggleReportBox} submitReport={this.reportSubmit} /> : '' }
</div>
);
}
}
export default ReportBugButton;
当点击报告按钮时,控制台日志完美地显示状态正在更新,因为它总是在“状态为:真”和“状态为:假”之间变化。
不幸的是,render 方法中的内联 if 似乎不太在意,因为如果状态为真,它不会显示组件。
如果我默认将状态设置为 true,则它会显示,但通过单击将其设置为 false 时不会隐藏。
有什么想法吗? ...:)
最佳答案
你正在以错误的方式改变状态。您应该永远不要直接修改状态变量。
使用this.setState
.
例如
this.setState({ report_toggle: !this.state.report_toggle });
只有当您调用此函数时,才会触发 render
函数并重新渲染(仅当某些状态变量发生变化时)。
关于javascript - ES6 react 状态变化不影响渲染内联 if 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823149/