[英]Passing props to handler function
我正在關注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
RoomButton
從給定的RoomButton
組件內部傳遞到handler
函數中?
嘗試將其傳入,並從React獲得Maximum depth reached
錯誤。
ES6的答案將不勝感激,順便說一句。
您可以嘗試以下解決方案:
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>
);
嘗試這個
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)
行實際上是使用一個參數(在本例中為.bind(null, room)
預加載處理程序函數。 這稱為“咖喱”。 如果您有計划,我將動作留在flipSwitch
參數列表中,但目前尚未使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.