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

时间:2017-06-08 20:29:35

标签: reactjs components state

我有两个按钮,点击后会更新一个计数器。我希望每个按钮都能更新自己的计数器。如何为每个按钮指定自己的状态,但同时使用相同的onClick方法?

这是我到目前为止的情况?

import React from 'react'
import Header from './Header'
import {Jumbotron,Badge, Glyphicon, Media, PageHeader, Button} from 'react-bootstrap'

class UpVote 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() {
    const item = this.state.item
    return (
      <div>
       <Button bsStyle="success" onClick={this.upVote}>
             {this.state.count}
      </Button>
      <hr />
      <Button bsStyle="success" onClick={this.upVote}>
          {this.state.count}
      </Button>
      </div>
    )
  }
}

export default UpVote

1 个答案:

答案 0 :(得分:1)

您可以定义一个新的按钮组件,用于跟踪其自身的状态,然后重复使用它。

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

在原始组件中执行:

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

class UpVote extends React.Component {

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

export default UpVote