当我使用这些导航器的库react-native-tab-navigator
移动页面来移动componentDidMount
页面时,只能完成一次,此后,生命周期组件将无法工作,请寻求解决方案:遵循我的代码。
我在Github上打开了一个问题,我尝试将状态发送给父母。我用过
react-native-tab-navigator版本0.3.4
class MainTab extends Component {
state = {
selectedTab: 'home'
};
render() {
return (
<
TabNavigator.Item selected = {
this.state.selectedTab === 'home'
}
title = "Home"
selectedTitleStyle = {
{
color: "#FF7158",
}
}
tabStyle = {
{
borderTopWidth: this.state.selectedTab === 'home' ? 3 : 0,
borderTopColor: '#FF7158',
backgroundColor: this.state.selectedTab === 'home' ? '#fff8f6' : '#FFFFFF'
}
}
renderIcon = {
() => < Image source = {
require('allComponents/images/ic_beranda.png')
}
style = {
{
width: 18,
height: 18
}
}
/>}
renderSelectedIcon = {
() => < Image source = {
require('allComponents/images/ic_beranda-actives.png')
}
style = {
{
width: 18,
height: 18
}
}
/>}
// renderBadge={() => <View style={{width: 20, height:20, backgroundColor:'#FF7158', borderRadius:50}}><Text style={{fontSize:12, textAlign:'center', color:'white', fontWeight:'600'}}>2}
onPress = {
() => this.setState({
selectedTab: 'home'
})
} >
<
/TabNavigator.Item> <
TabNavigator.Item
selected = {
this.state.selectedTab === 'profile'
}
title = "Pemesanan"
selectedTitleStyle = {
{
color: "#FF7158",
}
}
tabStyle = {
{
borderTopWidth: this.state.selectedTab === 'profile' ? 3 : 0,
borderTopColor: '#FF7158',
backgroundColor: this.state.selectedTab === 'profile' ? '#fff8f6' : '#FFFFFF'
}
}
renderIcon = {
() => < Image source = {
require('allComponents/images/ic_pemesanan-inactive.png')
}
resizeMode = 'stretch'
style = {
{
width: 18,
height: 18
}
}
/>}
renderSelectedIcon = {
() => < Image source = {
require('allComponents/images/ic_pemesanan-active.png')
}
resizeMode = 'stretch'
style = {
{
width: 18,
height: 18
}
}
/>}
onPress = {
() => this.setState({
selectedTab: 'profile'
})
} >
<
/TabNavigator.Item> <
TabNavigator.Item
selected = {
this.state.selectedTab === 'riwayat'
}
title = "Akun"
selectedTitleStyle = {
{
color: "#FF7158",
}
}
tabStyle = {
{
borderTopWidth: this.state.selectedTab === 'riwayat' ? 3 : 0,
borderTopColor: '#FF7158',
backgroundColor: this.state.selectedTab === 'riwayat' ? '#fff8f6' : '#FFFFFF'
}
}
renderIcon = {
() => < Image source = {
require('allComponents/images/ic_akun-inactive.png')
}
resizeMode = 'stretch'
style = {
{
width: 18,
height: 18
}
}
/>}
renderSelectedIcon = {
() => < Image source = {
require('allComponents/images/ic_akun-active.png')
}
resizeMode = 'stretch'
style = {
{
width: 18,
height: 18
}
}
/>}
onPress = {
() => this.setState({
selectedTab: 'riwayat'
})
} >
<
/TabNavigator.Item>
);
}
}
我希望componentDidMount
可以在TabBar上起作用。
答案 0 :(得分:0)
componentDidMount
在tabNavigator内时不会触发(预期第一次安装组件)。
原因是,当从一个选项卡切换到另一个选项卡时,每个选项卡都会被第一次渲染,而如果您一次聚焦它们,则所有选项卡都会被渲染。
我不知道您使用的是哪个导航器,但是通常您可以通过某种方式知道何时屏幕变得“聚焦”以及何时屏幕变得“模糊”。使用这些功能,您可以在每次“聚焦”屏幕时触发功能。
希望这可以帮助您更好地了解其工作原理!