嗨,我有一个反应应用程序,我返回几个按钮 . 我想要做的是取决于您单击另一个组件将在视图中显示和呈现的按钮 . 我已经在文档中查看了条件渲染,但我不确定如何将其与状态联系起来并呈现我所期望的 . 下面是组件中的最新示例 .
// import all the components I need;
class FormContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
dropdownVisible: false,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
if (!this.state.dropdownVisible) {
document.addEventListener('click', this.handleOutsideClick, false);
} else {
document.removeEventListener('click', this.handleOutsideClick, false);
}
this.setState(prevState => ({
dropdownVisible: !prevState.dropdownVisible,
}));
}
handleOutsideClick(e) {
if (this.node.contains(e.target)) {
return;
}
this.handleClick();
}
render() {
return (
<form className="form-container">
<h2>Browse The Database</h2>
// here are the two buttons
<button className="btn btn-default" onClick={this.handleClick}>
By Fiscal Year
</button>
<button className="btn btn-default" onClick={this.handleClick}>
By Research Organization
</button>
// depending on which one is clicked either of these table containers should render with the appropriate component passed in
<div className="table-container">{this.state.dropdownVisible && <FiscalYearTable />}</div>
<div className="table-container">
{this.state.dropdownVisible && <ResearchOrganizationTable />}
</div>
</form>
);
}
}
export default FormContainer;
发生的事情是只有一个是渲染,因为我没有 Build 每个按钮和我想渲染的组件之间的关系 . 如何使用与状态绑定的条件if或其他方法 Build 此关系?
3 回答
查看下面的代码 . 我添加了另一个状态变量'view',它从被单击的按钮获取视图的名称,并在render中检查要渲染的组件的状态值
尝试一下switch语句 .
所以每个按钮都可以有一个onClick事件,它传递你想要getView的视图 .
其他人建议的是,我之前也是这样做的,切换语句,基于按钮ID设置状态 . 这是你在找什么: