如何在Reactjs中为两个组件提供它们自己的状态?

如何在Reactjs中为两个组件提供它们自己的状态?,reactjs,components,state,Reactjs,Components,State,我有两个按钮,点击后将更新计数器。我希望每个按钮更新自己的计数器。如何为每个按钮提供其自己的状态,但同时使用相同的onClick方法 这是我到目前为止所做的吗 从“React”导入React 从“./头”导入头 从“react bootstrap”导入{Jumbotron、徽章、Glyphicon、媒体、页眉、按钮} 类upreact.Component{ 建造师(道具){ 超级(道具) 此.state={ 计数:0 } this.upVote=this.upVote.bind(this) }

我有两个按钮,点击后将更新计数器。我希望每个按钮更新自己的计数器。如何为每个按钮提供其自己的状态,但同时使用相同的
onClick
方法

这是我到目前为止所做的吗

从“React”导入React
从“./头”导入头
从“react bootstrap”导入{Jumbotron、徽章、Glyphicon、媒体、页眉、按钮}
类upreact.Component{
建造师(道具){
超级(道具)
此.state={
计数:0
}
this.upVote=this.upVote.bind(this)
}
向上投票(){
这是我的国家({
计数:this.state.count+1
})
}
render(){
const item=this.state.item
返回(
{this.state.count}

{this.state.count} ) } }
导出默认UpVote
您可以定义一个新的按钮组件,该组件跟踪自己的状态,然后重用它

import React from 'react'
import { Button} from 'react-bootstrap'

class UpVoteButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 0
    }

    this.upVote = this.upVote.bind(this)
  }

  upVote() {
    this.setState({
      count: this.state.count + 1
    })
  }

  render() {
    return (
       <Button bsStyle="success" onClick={this.upVote}>
             {this.state.count}
      </Button>
    )
  }
}

export default UpVoteButton
从“React”导入React
从“react bootstrap”导入{Button}
类UpVoteButton扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
计数:0
}
this.upVote=this.upVote.bind(this)
}
向上投票(){
这是我的国家({
计数:this.state.count+1
})
}
render(){
返回(
{this.state.count}
)
}
}
导出默认UpVoteButton
在原始组件中,请执行以下操作:

import React from 'react'
import UpVoteButton from './UpVoteButton'

class UpVote extends React.Component {

  render() {
    return (
      <div>
        <UpVoteButton/>
        <hr />
        <UpVoteButton/>
      </div>
    )
  }
}

export default UpVote
从“React”导入React
从“/UpVoteButton”导入UpVoteButton
类upreact.Component{
render(){
返回(

) } } 导出默认向上投票
如果使用upVote组件中的upVote方法,则始终会增加upVote组件的状态。那么,你认为每个按钮都有一个单独的计数,但在两个组件中都保留这个方法,这就是为什么我要问这个问题。我是新手。