我试图点击一个反应按钮,并显示一个表格。按钮应该返回一个表,但是当我点击它时它什么也不返回。任何人都可以帮忙吗?非常感谢!
我的功能
const getSchedule = () => {
return (
<div>
<Table striped bordered hover>
<thead>
<tr>
<th>Schedule Id</th>
<th>Trainer Id</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{/* {schedule.map(render_schedule)} */}
</tbody>
</Table>
</div>
)
}
我的按钮:
答案 0 :(得分:2)
let check=false
const getSchedule = () => {
check=True
};
在您的主函数返回中,如果 check 为 True(检查初始化为 False 并单击按钮将其设置为 True ),则使用类似这样的内容来显示您的表格:
{check && <div>..your table code here </div>}
您的 onClick 处理程序保持不变:
<button onClick={getSchedule}>show table</button>
答案 1 :(得分:1)
这是因为即使您返回了表格 div,页面 react 也不会重新渲染页面。
React 仅在状态改变时重新渲染页面
假设您想在按钮下方显示表格,您可以这样做:-
<Button onClick={()=>getSchedule()}>Search Schedule</Button>
<div>{this.state.schedule}</div>
在状态中创建时间表
constructor(props)
{
super(props);
this.state = { schedule:[]};
}
而不是最后在您的 getSchedule 中,您需要使用 setState() 分配所有要安排的 HTML 内容
const getSchedule = () => {
let newSchedule = [];
newSchedule.push(<div><Table>.......</div>);
this.setState({schedule:newSchedule});
}
这里最初 this.state.schedule 将是空的所以什么都不渲染,但是当我们更新 schedule 和 setState 它会重新渲染页面但现在 this.state.schedule 将有你的表格 HTML