单击按钮时增加变量的值

时间:2021-03-08 10:22:52

标签: reactjs

我有两个名为 App.Jsindex.js 的 JS 文件。每次单击按钮时,我都想增加 count 变量的值。我在 index.js 中呈现 html 元素,并在 onclick 中编写了 App.js 方法代码。但它不起作用。这是我试过的代码:

App.js

enter image description here

index.js

enter image description here

3 个答案:

答案 0 :(得分:0)

在 App 组件内移动按钮。在 index.js 中只呈现应用程序。

答案 1 :(得分:0)

请按如下方式更新您的应用组件:

import React, { Component } from 'react'

export default class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      count:0
    }
  }
  handleClick(){
    this.setState((prevState)=>{
      return {
       count: prevState.count+1
      }
    })
  }
  render() {
    return (
    <button onClick={this.handleClick.bind(this)}>{this.state.count}</button>
    )
  }
}

此外,从 index.js 中删除未使用的类 Count。

答案 2 :(得分:0)

您在 App 组件中定义了方法。在同一组件中定义按钮:

 class App extends Component {
     constructor(props) {
            super(props)
    this.state={count:0}
     this.handeleClick=this.handeleClick.bind(this);
    }
    
    handeleClick(){
    this.setState(prevState=>
    return {
           count: prevState.count+1
          }
    )
     render() {
        return (
        <button onClick={this.handeleClick}>{this.state.count}</button>
        )
      }
 }
export default App

依此类推:

class Count extends Component {
render() {
  return (
   <App/>
  )
}
}
ReactDOM.render(<Count />, document.getElementById('root'));
相关问题