我正在关注Pure React,并且有一个House
组件需要一些构造(为简洁起见,省略了导入):
class House extends React.Component {
state = {
bathroom: true,
bedroom: false,
kitchen: true,
livingRoom: false
}
flipSwitch = (action) => {
this.setState({
???????????????
});
}
render () {
return (
<>
<RoomButton room='kitchen' handler={this.flipSwitch}/>
<RoomButton room='bathroom' handler={this.flipSwitch}/>
<RoomButton room='livingRoom' handler={this.flipSwitch}/>
<RoomButton room='bedroom' handler={this.flipSwitch}/>
</>
);
}
}
const RoomButton = ({room, handler}) => (
<button onClick={handler}>
{`Flip light in ${room}!`}
</button>
)
ReactDOM.render (
<House/>,
document.getElementById('root')
)
期望的结果:单击<room>
按钮时,House
组件的状态将发生变化,以反映房间内的电灯开关的翻转(即,true点亮,false熄灭)
我想知道应该怎么做而不是?????
-如何从给定的room
组件内部将handler
道具传递到RoomButton
函数中? / p>
尝试将其传入,并从React收到一个Maximum depth reached
错误。
ES6的答案将非常感谢,顺便说一句。
答案 0 :(得分:5)
您可以尝试以下解决方案:
flipSwitch
将接受房间名称作为参数,并使用回调更新状态(以获取当前状态的正确值)
class House extends React.component {
....
flipSwitch = room => {
this.setState(state => ({
[room]: !state[room]
});
}
...
}
const RoomButton = ({room, handler}) => (
<button onClick={() => handler(room)}>
{`Flip light in ${room}!`}
</button>
);
答案 1 :(得分:3)
尝试一下
flipSwitch = (room, action) => {
this.setState((prevState) => ({
[room]: !prevState[room]
}));
}
const RoomButton = ({room, handler}) => (
<button onClick={handler.bind(null, room)}>
{`Flip light in ${room}!`}
</button>
)
.bind(null, room)
行实际上是使用一个参数(在本例中为room)预加载处理程序函数。这称为“咖喱”。如果您有计划,我会在flipSwitch
参数列表中保留操作,但目前尚未使用。