【问题标题】:React JS Change graph html code by onClickReact JS 通过 onClick 更改图形 html 代码
【发布时间】:2018-10-05 04:31:35
【问题描述】:

嗨,我开始学习 react.js

我想做的是按下下面的按钮

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

将加载 html 代码

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

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

【问题讨论】:

  • 您可能只需要将this.state.clickMonth 替换为this.clickMonth :)

标签: javascript reactjs chartjs-2.6.0


【解决方案1】:

您的代码应该如下所示。

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

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

【讨论】:

  • 嗨,如果我也有季度和年份按钮的话。我应该在构造函数中和渲染后添加 clickQuarter、clickYear 吗?
  • @PlataleaMinor 是的。如果你想在不同的按钮点击上调用不同的组件,你应该遵循这个原则。如果您想始终渲染组件,则不需要条件渲染
  • 最后一个问题。如何隐藏其他不相关的图表?现在,当我按下任何一个时,所有三个图表都会弹出。提前谢谢你
  • @PlataleaMinor 当单击另一个按钮时,使用 setState 使其他两个按钮状态为 false,这样只有一个组件将呈现单击该按钮的组件
  • @PlataleaMinor 我更新了我的答案有不同之处请看一下
猜你喜欢
  • 2021-03-08
  • 2020-10-06
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2012-03-29
  • 1970-01-01
相关资源
最近更新 更多