javascript - React JS 通过 onClick 更改图表 html 代码

标签 javascript reactjs chartjs-2.6.0

嗨,我开始学习react.js

我想做的是按下面的按钮

<Button
color="primary"
onClick={this.state.clickMonth}>

将加载 html 代码

clickMonth = () =>{
  this.setState({
  month: <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />
  })
}

但是,它不起作用。如果需要,我可以提供更多信息。谢谢您的帮助

最佳答案

您的代码应该如下所示。

react 中的事件处理函数可以通过 this.functionName 调用,但不能通过 this.state.functionName 调用。在你的情况下,它应该是 this.clickMonth 但不是 this.state.clickMonth

现在,单击按钮即可渲染 Line 组件。因此,要在单击按钮时渲染 Line 组件,您可以将 bool 标志设置为 true 并相应地渲染 Line 组件,就像我在下面所做的那样

constructor(props){
  super(props);
  this.state = {
    showLine: false,
    showLine1: false
  }
}
clickMonth = () =>{
  this.setState({
     showLine: true,
     showLine1: false
  })
}

clickYear = () =>{
  this.setState({
     showLine: false,
     showLine1: true
  })
}

render(){
   const { showLine, showLine1 } = this.state;
   return(
     <div>

        {showLine && <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />}
        {showLine1 && <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />}
        <Button color="primary" onClick={this.clickMonth} />
        <Button color="primary" onClick={this.clickYear} />
     </div>
   )
}

关于javascript - React JS 通过 onClick 更改图表 html 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52658387/

相关文章:

javascript - Firebase 日志事件

reactjs - 如何根据本地存储设置Mui主题?

mysql - 使用 mySql 的简单 React 无法读取表记录

reactjs - Devextreme DataGrid 与 Ag-Grid 相比如何进行 react

javascript - 图表 js。如何通过工具提示的中心对齐文本?

javascript - jQuery。 .load() 不会给出响应/状态

javascript - 将项目添加到 json 对象

javascript - 数据表和 Firebase Web

javascript - 减少条形间距 ChartJS v2

javascript - 让 Chartjs 显示数据标签的键而不是值