【发布时间】:2020-04-01 23:58:29
【问题描述】:
已编辑
所以我有一个计数器按钮组件,我在我的应用程序中呈现它。我的应用程序包含计数器的状态,但我如何将它作为道具传递给 Counter 组件?目前 Counter 有自己的状态,但我希望它使用 App 中的状态。
我还试图在一个单独的组件中创建一个通用计数器按钮,它将增加/减少重复的计数器按钮。但是我有同样的问题,我不确定如何正确地将应用程序的状态作为道具传递到这个通用按钮中。
万能计数器:
class UniversalCounter extends Component {
constructor(props) {
super(props);
const allCounter = [Counter]
this.state = allCounter;
}
incrementCount() {
this.setState(prevState => ({ allCounter: prevState.allCounter + 1 }));
}
decrementCount() {
this.setState(prevState => ({ allCounter: prevState.allCounter - 1 }));
}
render() {
let { allCounter } = this.state;
return (
<div>
<h2>All Counters</h2>
<button onClick={() => this.incrementCount(allCounter)}>increase all</button>
<button onClick={() => this.decrementCount(allCounter)}>decrease all</button>
</div>
);
}
计数器组件:
class Counter extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
incrementCount() {
this.setState(prevState => ({ counter: prevState.counter+ 1 }));
}
decrementCount() {
this.setState(prevState => ({ counter: prevState.counter- 1 }));
}
render() {
let { counter} = this.state;
return (
<div>
<h2>Count: {counter}</h2>
<button onClick={() => this.incrementCount(counter)}>+</button>
<button onClick={() => this.decrementCount(counter)}>-</button>
</div>
);
}
}
应用:
class App extends Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
}
render() {
let { counter } = this.state;
return (
<div className="App">
<Counter/>
<Counter/>
<Counter/>
<UniversalCounter />
</div>
);
}
}
export default App;
【问题讨论】:
-
移动 all 状态到父状态。你不想要多个事实来源。
-
但如果通用按钮是唯一一个计数器处于状态的按钮,其他按钮将不起作用。
-
你能展示一下它的外观吗?
标签: javascript reactjs counter