javascript - 反应:在从另一个组件调用的函数中使用 setState?
问题描述
我从 ReactJS 开始,我正在为我的 React 游戏做一个评分系统。
我使用了一个名为 Score 的组件来管理它。
我在状态下做了一个分值,可以递增increment()
.
问题是我想从我的 App 组件中使用这个函数(这是一个例子,我创建它是incrementScore()
为了展示它)。
但是,我increment()
无法访问this.setState()
从另一个组件调用该函数的时间。
请注意,我在Score.js
其中创建了一个“增量”按钮increment()
,它可以完美地工作。
您有解决方案还是可以提供线索?谢谢!
应用程序.js:
import Score from './Score'
class App extends React.Component {
incrementScore() {
Score.prototype.increment()
}
render() {
return (
<div>
<h1 id="title">Game</h1>
<Score />
<Canvas /> {/*Not important here, just for the game*/}
</div>
)
}
}
export default App
分数.js:
import React from 'react'
class Score extends React.Component {
constructor() {
super()
this.state = {
score: 0
}
this.increment = this.increment.bind(this)
}
increment() {
this.setState({
score: this.state.score + 1 //this.state.score + 1
})
}
render() {
return (
<div>
<p id="score">Score: {this.state.score}</p>
<button>Incrementer</button>
</div>
)
}
}
export default
解决方案
正如 Robin 所说,只需将您的状态移动到您的父App
组件,并让您的Score
组件成为“无状态”组件。此外,请确保将增量函数作为道具向下传递,并在按钮中将其用作onClick
函数。
class App extends React.Component {
constructor() {
super()
this.state = {
score: 0
}
this.increment = this.increment.bind(this)
}
increment() {
this.setState({
score: this.state.score + 1 //this.state.score + 1
})
}
render() {
return (
<div>
<h1 id="title">Game</h1>
<Score scoreCount={this.state.score} increment={this.increment}/>
</div>
)
}
}
const Score = props =>
<div>
<p id="score">Score: {props.scoreCount}</p>
<button onClick={props.increment}>Incrementer</button>
</div>
在此处查看实时示例:https ://codesandbox.io/s/wq4kqqz0mw
推荐阅读
- java - 以编程方式在表内创建的 JSF commandLink 不起作用
- config - $wgSitename 中的特殊字符
- python - RuntimeError:PyTorch 目前不提供 PyPI 包
- php - PHP表单提交上的文件上传可选
- java - 数组索引超出try catch中的绑定异常处理
- datatable - 如何在 ComboBox SelectedIndexChanged 事件的文本框中获取 DataTable 列值?
- python-3.x - Holoviews - 选择抛出 AttributeError 的图
- xcode - Xcode Storyboards 现在只显示大纲
- highcharts - R Highcharter:通过单击突出显示/取消突出显示条形图中的条形
- python - 在 PyCharm 中运行带有 GPU 支持的 Tensorflow 内存不足