我對缺少工作代碼表示歉意,但我不確定如何去做這件事,因此它是非工作代碼。我希望在更改ToggleBox的狀態時更新App類中的this.state.count。我確信之前已經問過這個問題,提前感謝。ReactJS - 當子狀態發生變化時更新父狀態
import React, { Component } from 'react';
import ToggleBox from '../components/ToggleBox';
class App extends Component {
constructor(props) {
super(props);
this.state = {
total : 60,
count: 0
};
}
getToggles() {
let toggles = [];
for (let i = 0; i < this.state.count; i++) {
toggles.push(<ToggleBox checked={false} key={i} />);
}
return toggles;
}
render() {
let toggles = this.getToggles();
return (
<div className="App">
{{this.state.count}} - {{this.state.total}}
<div className="container-toggle-box">
{toggles}
</div>
</div>
);
}
}
export default App;
...和組件:
import React, {Component} from 'react';
class ToggleBox extends Component {
constructor(props) {
super(props);
this.state = {
active = this.props.checked
};
this.handleClick= this.handleClick.bind(this);
}
handleClick() {
this.setState({active: (this.state.active) ? false : true}
}
render() {
let mark = (this.state.active) ? 'x' : 'o'
return (
<span>
{mark}
</span>
);
}
}
export default ToggleBox;
你只是在那裏渲染組件,你想用標記上的onClick事件來改變某個狀態?設置該道具並通過該功能。 – bntzio