所以我有一个滑块和一个停止滑块并重新启动滑块的方法,但我需要根据子组件的状态停止滑块,所以如果用户按下子组件,状态会改变,我需要停止滑块,但该功能在滑块组件中,我如何从子组件调用该函数,这是我的子组件。
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组件,当child的state为true时会停止slider,当为false时会重启slider
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}”,但无法正常工作
我想你应该这样做的方法是将函数传递给孩子,然后孩子们调用该函数,但如果我有 this.props.chlidren,我不知道该怎么做
答案 0 :(得分:1)
您可以像这样将函数传递给子组件:
<Child onPress={() => this.pressHandler()}/>
并且您必须向组件 SliderPromotions 添加一个函数 pressHandler。
pressHandler= () =>
{
// Add your logic when the state Promotion is false
// Add your logic when the state Promotion is true
}