如何在 Reactjs 中给两个组件自己的状态?
How to give two components their own State in Reactjs?
我有两个按钮,点击它们会更新一个计数器。我希望每个按钮都更新自己的计数器。如何为每个按钮赋予其自己的状态,但同时使用相同的 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
您可以定义一个新的按钮组件来跟踪其自身的状态,然后重新使用它。
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
我有两个按钮,点击它们会更新一个计数器。我希望每个按钮都更新自己的计数器。如何为每个按钮赋予其自己的状态,但同时使用相同的 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
您可以定义一个新的按钮组件来跟踪其自身的状态,然后重新使用它。
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