假设我有三个元素保持状态,一个计数器在点击时递增。
如果单击一个元素,如何将其他计数器重置为0?
https://jsfiddle.net/69z2wepo/56827
const Parent = React.createClass({
render() {
const rows = [];
for (let i = 0; i < 3; i++) {
rows.push(<Child key={i} />);
}
return (
<ul>
{rows}
</ul>
);
}
});
const Child = React.createClass({
getInitialState() {
return {counter: 0};
},
handleClick() {
this.setState({counter: ++this.state.counter });
},
render() {
return (
<div onClick={this.handleClick}>
{this.state.counter}
</div>
);
}
});
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
答案 0 :(得分:3)
由于您的Child
组件正在管理自己的状态,因此会有点困难。
您可以将它们转换为哑组件,并在Parent
组件中管理其状态。
像这样的东西
const Parent = React.createClass({
getInitialState() {
return {counters: [0,0,0]};
},
handleClick(index){
let newCounterState = this.state.counters.map(() => 0);
newCounterState[index] = this.state.counters[index] + 1 ;
this.setState({counters : newCounterState})
},
render() {
const rows = this.state.counters.map((value,index) => (
<Child
key={index}
handleClick={() => this.handleClick(index)}
counter={value}
/>
))
return (
<ul>
{rows}
</ul>
);
}
});
const Child = ({counter,handleClick}) => (
<div onClick={handleClick}>
{counter}
</div>
)
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
答案 1 :(得分:1)
答案 2 :(得分:1)
你真的可以像其他答案所暗示的那样lift the state进入父组件,这样做的一种愚蠢的方法就是改变元素的key
道具。这会导致React使用旧key
卸载元素并挂载新实例。
class ChildComponent extends React.Component {
state = {
count: 0
};
render() {
const { count } = this.state;
return (
<div>
<div>count: {count}</div>
<button onClick={() => this.setState({ count: count + 1 })}>Increment</button>
</div>
);
}
}
class ParentComponent extends React.Component {
state = {
stateBustingKey: 0
};
render() {
const { stateBustingKey } = this.state;
return (
<div>
<ChildComponent key={stateBustingKey} />
<button
onClick={() =>
this.setState({ stateBustingKey: stateBustingKey + 1 })
}
>
Reset
</button>
</div>
);
}
}
ReactDOM.render(<ParentComponent />, document.getElementById("root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
&#13;