javascript - 如何修复 1 状态差距?
问题描述
我正在练习将状态发送到子组件 - 父组件 - 另一个子组件。
我被困在我的练习中,
首先,我成功地制作了像这个 子组件这样的反应计数器
其次,我想将计数器值发送到另一个组件。我知道如何将状态发送到另一个子组件。但我坚持我的工作。
当我第一次单击 + 按钮时,它只适用于第一个孩子。然后,当我再次单击时,它也适用于另一个孩子(不匹配数字)
我该如何处理这个问题?
这是我的代码。
// This is Counter.js
class Counter extends Component {
state = {
counter: 0
}
handleIncrement = () => {
this.setState(({ counter }) => ({
counter: counter + 1
}))
this.props.handleCounter(this.state.counter)
}
handleDecrement = () => {
this.setState(({counter}) => ({
counter: counter - 1
}))
this.props.handleCounter(this.state.counter)
}
render() {
return (
<div>
<h1>Counter</h1>
<h3>{this.state.counter}</h3>
<button onClick={this.handleIncrement}>+</button>
<button onClick={this.handleDecrement}>-</button>
</div>
)
}
}
// This is App.js file
import Counter from './components/counter';
import Sent from './components/sent'
class App extends React.Component {
state = {
counter: this.handleCounter
}
handleCounter = (counter) => {
console.log("Received Count 1 ")
this.setState({
counter: counter
})
}
render() {
return (
<div className="App">
<Counter handleCounter={this.handleCounter} />
<Sent result={this.state.counter} />
</div>
);
}
}
// This is Sent.js file
import React, { Component } from 'react'
class Sent extends React.Component {
render() {
return (
<div>
<h2>Result ==> {this.props.result}</h2>
</div>
)
}
}
解决方案
推荐阅读
- validation - 表单数据验证
- c# - MVC Core 存储库查询选择所有列
- r - 如何找出新的 NaN 来自哪里 - R
- jquery - 无法在 jQuery 对话框按钮功能中放置 ajax 调用。返回空
- java - jackson kotlin - 无法从 START_OBJECT 令牌中反序列化 `java.util.ArrayList` 的实例
- javascript - Mapbox 在点击事件上更改缩放
- tfs - 使用 TFS 计划备份/还原将 TFS 2015 数据库还原到 TFS 2018 失败
- dojo - 在 XPages 中设置 Dojo 时间选择器的开始时间和结束时间
- elasticsearch - ElasticSearch/Kibana:时区从 UTC 更改为东部
- sql - PARTITION BY 表达式引用既不分组也不聚合的列 sku