javascript - 我如何重用几乎没有变化的 React 组件
问题描述
我想使用 React重新创建类似的东西。我还想为 2 个玩家使用 1 个玩家组件。既然两个玩家都有一个递增和递减按钮,那我如何让 App.js 区分这两个玩家之间的区别呢?我知道我可能可以将它作为参数传递,但我在哪里设置呢?
这就是我为 App.js 所拥有的,显然它适用于单个玩家:
constructor(props) {
super(props);
this.state = {
player1: 20,
player2: 20
};
}
increment = () => {
this.setState({
player1: this.state.player1 + 1,
player2: this.state.player2
};
解决方案
您可以将参数传递给您的增量函数,指示它是哪个播放器
increment = (p) => {
this.setState({
[p]: this.state[p] + 1,
};
并相应地将处理程序传递给 Player 实例:
return (
<Player increment={() => { this.increment('player1') }} />
<Player increment={() => { this.increment('player2') }} />
)
在您的 Player 组件中,您会执行类似的操作
const Player = (props) => {
return (
// I assume you would have some button somewhere
<button onClick={() => { props.increment() }}
)
}
推荐阅读
- javascript - Google Sheets 可安装触发器:整个函数在 try-catch 中,但仍然会出现错误
- asp.net-mvc - 如何根据语言环境从控制器中设置选定的剑道下拉列表值?
- wso2 - 如何使用自定义组件从 ESB 注册表(在 linux 环境中)加载变量
- c++ - cpp_int (boost) 运行时错误:解析字符串时发现意外内容
- github - travis-ci 中的工作服输出没有可用的报告文件,并且 repo 令牌为空
- heroku - 使用 Heroku 和 Amazon S3 上的 Active Storage 使用上传的 Roo gem 打开远程文件
- sql - 对象名称无效,但对象显然有效
- java - 如何为多个模块配置 Log4J2?
- .net - 这种时间格式有名称吗?
- scala - 如果对象中的某些字段相同,则对象的scala过滤器列表