[英]Call parent function from child
so i have a slider and a method to stop the slider and restart the slider, but i need to stop the slider based on the state of the children, so if the user press the child component the state change and i need to stop the slider但是 function 在 slider 組件中,我怎么能從孩子那里調用 function 這是我的孩子組件。
class SliderPromotions extends React.Component
{
constructor()
{
super();
this.state =
{
Promotion: false
}
}
ShowPromotion = () =>
{
this.setState({ Promotion: !this.state.Promotion });
}
render()
{
return (
<Slider StopSlider={this.state.Promotion}>
{
Data.map(function(DataValue)
{
return (
<Child onPress={() => this.ShowPromotion()}/>
);
}, this)
}
</Slider>
);
}
}
這是 slider 組件,當子組件的 state 為 true 時將停止 slider,當為 false 時將重新啟動 Z10ZBF58F0BBDAE468B9474
class Slider extends React.Component
{
StopSlider = () =>
{
//this stop the slider
//.......
//I try this when I pass the prop but doesn't work
if(!this.props.StopSlider)
{
}
}
RestartSlider = () =>
{
//this restart the slider
}
render()
{
return (
<ScrollView>
{
this.props.children
}
</ScrollView>
);
}
}
所以我嘗試從 Slider 組件中的 SliderPromotion 傳遞一個道具,例如“StopSlider = {this.state.Promotion}”,但不能正常工作
我在想你應該這樣做的方式是將 function 傳遞給孩子們,然后孩子們稱之為 function 但如果我有 this.props.chlidren 我不知道該怎么做
您可以將 function 傳遞給您的子組件,如下所示:
<Child onPress={() => this.pressHandler()}/>
您必須將 function pressHandler 添加到您的組件 SliderPromotions。
pressHandler= () =>
{
// Add your logic when the state Promotion is false
// Add your logic when the state Promotion is true
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.