[英]How to pass different event handlers for the same event?
我有一個 react-native 組件,它渲染了 2 個圖標,用於標記收藏夾和寫評論,如下所示:
function RenderDish(props) {
const dish = props.dish;
if (dish != null) {
return (
<Card featuredTitle={dish.name} image={{ uri: baseUrl + dish.image }}>
<Text style={{ margin: 10 }}>
{dish.description}
</Text>
<View style={{ display: "flex", flexDirection: "row", alignItems: "center", justifyContent: "center" }}>
<Icon raised reverse name={props.favorite ? 'heart' : 'heart-o'} type='font-awesome' color='#f50'
onPress={() => props.favorite ? console.log('Aleady Favorite') : props.onFavorite()} />
<Icon raised reverse name='pencil' type='font-awesome' color='#3b5998'
onPress={() => props.onComment()} />
</View>
</Card>
);
}
else {
return (<View></View>);
}}
我從外部組件調用這個功能組件,如下所示:
<RenderDish dish={this.props.dishes.dishes[+dishId]}
favorite={this.props.favorites.some(el => el === dishId)}
onFavorite={() => this.markFavorite(dishId)}
onComment={() => this.toggleModal()} />
我已經實現了toggleModal()
和markFavorite()
方法,一切都按預期工作,但我的問題是:有沒有其他方法可以通過單個 prop 傳遞 2 個或更多不同的事件處理程序? 例如。 有什么辦法可以這樣說: <RenderDish dish={xyz} onPress={()=> handler1 AND handler2}
。 或者有沒有什么優雅的替代品來代替我所做的(如果我有 5 個按鈕,我需要 5 個道具:()?
您可以將處理程序放在一個函數中,並在 onPress 中調用該函數。 要不就
onPress={()=> {handler1, handler2}}
嘗試類似下面的內容。 將處理程序方法作為道具中的對象傳遞。
function Button(props) {
return (
<div>
<button type="button" onClick={props.onPress.handler1} >Handler1</button>
<button type="button" onClick={props.onPress.handler2} >Handler2</button>
</div>
);
}
class Home extends Component {
handler1() {
console.log('handler 1');
}
handler2() {
console.log('handler 2');
}
render() {
return (
<div>
<Button onPress={{ handler1: this.handler1, handler2: this.handler2 }} />
</div>
)
}
}
你這樣做的方式可能是最常見的方式,也是完全可以接受的。
如果只有幾個處理程序(並且它們沒有被深入傳遞),這通常不是問題。
您可以將它們捆綁到一個對象和單個道具中,但我通常不認為這樣做會帶來很大的好處。
您還可以將多個道具作為單個展開對象傳入,而無需將它們捆綁到單個道具中。
如果您開始獲得比您適應的更多的處理程序,那么這可能是查看您如何處理狀態管理的好時機。 在這一點上,使用減速器和分派動作可能會更好。
關於您的代碼的其他一些注意事項:
View
結束標記。function RenderDish({dish, favorite, onFavorite, onComment}) =>
dish
? <Card featuredTitle={dish.name} image={{ uri: baseUrl + dish.image }}>
<Text style={{ margin: 10 }}>
{dish.description}
</Text>
<View style={{ display: "flex", flexDirection: "row", alignItems: "center", justifyContent: "center" }}>
<Icon raised reverse name={favorite ? 'heart' : 'heart-o'} type='font-awesome' color='#f50'
onPress={() => favorite ? console.log('Aleady Favorite') : onFavorite()} />
<Icon raised reverse name='pencil' type='font-awesome' color='#3b5998'
onPress={onComment} />
</View>
</Card>
: <View/>
我會更多地關注這些項目,而不是捆綁這兩個功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.