【问题标题】:How to give two components their own State in Reactjs?如何在 Reactjs 中给两个组件自己的状态?
【发布时间】:2017-11-10 17:11:22
【问题描述】:

我有两个按钮,点击后会更新计数器。我希望每个按钮都更新自己的计数器。我怎样才能给每个按钮自己的状态,但同时使用相同的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

【问题讨论】:

  • 如果您使用 UpVote 组件中的 upVote 方法,您将始终增加 UpVote 组件的状态。那么您如何想象对每个 Button 进行单独计数但在两个组件中都保留此方法?
  • 这就是我问这个问题的原因。我是 reactjs 新手。

标签: reactjs components state


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 2021-01-03
    • 1970-01-01
    • 2020-06-19
    • 2021-03-30
    • 1970-01-01
    • 2019-02-11
    • 2019-10-14
    • 1970-01-01
    相关资源
    最近更新 更多