【发布时间】:2020-08-27 01:48:05
【问题描述】:
警告:对仍在学习的新手做出反应。
我有一个挑战,需要我构建一个简单的 React Counter 应用程序。规则是:不使用 Redux,不使用钩子。每个计数器都独立地通过单击按钮来增加或减少。和! Parent 组件可以递增或递减所有 Counter 组件。
单个递增/递减的EX:
计数器 1 = 2
计数器 2 = 4
计数器 3 = 6
EX Increment ALL 将进行以下更改:
计数器 1 = 3
计数器 2 = 5
计数器 3 = 7
我知道这涉及在父组件中定义的回调函数,我只是对如何实现它感到困惑。我现在有一种非常低效的方法来做到这一点。谁能引导我以更有效的方式进行设置?
这是我的父母:
import React from 'react';
import Counter from './components/Counter';
class App extends React.Component {
constructor(props) {
super(props);
this.counterElement1 = React.createRef();
this.counterElement2 = React.createRef();
this.counterElement3 = React.createRef();
}
handleAllIncrease = () => {
console.log("hello App Increase")
this.counterElement1.current.handleIncrease();
this.counterElement2.current.handleIncrease();
this.counterElement3.current.handleIncrease();
}
handleAllDecrease = () => {
console.log("hello App Decrease")
this.counterElement1.current.handleDecrease();
this.counterElement2.current.handleDecrease();
this.counterElement3.current.handleDecrease();
}
render() {
return (
<div className="App">
<button onClick={() => this.handleAllIncrease()}>Increase all</button>
<button onClick={() => this.handleAllDecrease()}>Decrease all</button>
<Counter ref={this.counterElement1} />
<Counter ref={this.counterElement2}/>
<Counter ref={this.counterElement3}/>
</div>
);
}
}
export default App;
这是我的孩子:
import React from 'react';
class Counter extends React.Component {
state = {
num: 0,
}
handleIncrease = () => {
console.log("hello increase")
this.setState({
num: this.state.num + 1,
})
}
handleDecrease = () => {
console.log("hello decrease")
this.setState({
num: this.state.num - 1,
})
}
render() {
return (
<div>
<p>{this.state.num}</p>
<button onClick={this.handleIncrease}>+</button>
<button onClick={this.handleDecrease}>-</button>
</div>
)
}
}
export default Counter;
【问题讨论】:
标签: reactjs components parent-child counter