通过onClick反应JS更改图形html代码

时间:2018-10-05 04:31:35

标签: 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} />
  })
}

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

1 个答案:

答案 0 :(得分:1)

您的代码应如下所示。

react中的事件处理函数可以使用this.functionName调用,但不能使用this.state.functionName调用。您的情况应该是this.clickMonth,而不是this.state.clickMonth

现在,单击按钮即可渲染“线”组件。因此,要在单击按钮时渲染Line组件,您可以将boolean标志设置为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>
   )
}