这几天一直在弄动态修改react-navigation的各种属性的方法,想做成额效果如下:
上面是有一个导航栏的,然后导航栏上面有两个view,就是左边的定位和右边的搜索,然后导航栏的透明度可以动态调整,这里弄了一个text的点击来调整透明度,其实是想要根据Scrollview的偏移量来调整的,不过还没弄。
之前看网上的教程,照着他们的方式来传递参数,然后得到的全是一堆undefined…,这里将我的代码贴出来参考一下:
render() {
const { setParams } = this.props.navigation;
return (
<ScrollView style={styles.container} onSrcollBeginDrag={this._onScroll}>
<ImageViewPager
style={styles.viewPagerStyle}
dataSource={this.state.dataSource}
renderPage={this._renderPage}
locked={true}
isLoop={true}
autoPlay={true}
/>
<Text style={{fontSize:25}} onPress={() => setParams({locationTitle:this._setNewLocationTitle(),locationWidth:this._getLocationWidth()})}>测试地址变更</Text>
<Text style={{fontSize:25}} onPress={() => setParams({navigationBackGroundColor:this._getNavigatorBackgroundColor()})}> 测试导航栏透明度 </Text>
<Text> 当前透明度为{this.state.navigatorOpacity}</Text>
</ScrollView>
);
}
注意第二行的const { setParams } = this.props.navigation;
在StackNavigator中注册后的组件都有navigation这个属性. navigation又有5个参数:navigate, goBack, state, setParams, dispatch,我这里用到了setParams。
componentDidMount(){
// 通过在componentDidMount里面设置setParams将title的值动态修改
this.props.navigation.setParams({
headerTitle:'',
tabBarLabel:'',
locationTitle:this.state.locationTitle,
locationWidth:this.state.locationWidth,
opacity:this.state.navigatorOpacity,
navigationBackGroundColor:this.state.navigationBackGroundColor,
});
}
然后配置导航栏参数:
static navigationOptions = ({navigation,screenProps}) => ({
headerTitle:navigation.state.params?navigation.state.params.headerTitle:'Test2',
tabBarLabel:navigation.state.params?navigation.state.params.tabBarLabel:'Test2',
headerStyle:{
backgroundColor:navigation.state.params?navigation.state.params.navigationBackGroundColor:'red',
},
headerLeft:(
<View style={{
flexDirection:'row',
marginLeft:10,
marginRight:5,
width:navigation.state.params?navigation.state.params.locationWidth:1,
height:20,
backgroundColor:'rgba(31,35,32,0.4)',
borderRadius: 7,
}}>
<Icon name={'map-marker'} size={15} style={{marginLeft:6,marginTop:2}} color={'white'}/>
<Text style={{color:'white',marginTop:1.5,marginRight:2}}>{navigation.state.params?navigation.state.params.locationTitle:'Test2'}</Text>
</View>
),
headerRight:(
<View style={{
flexDirection:'row',
backgroundColor:'white',
borderRadius: 7,
marginRight:10,
height:20,
width:deviceWidth / 2 -10,
}}>
<Icon name={'search'} size={12} color={'black'} style={{
marginTop:3,
marginLeft:5,
}}></Icon>
<TextInput
style={{
fontSize:13,
marginLeft:3,
}}
placeholder={'搜索所有商品'}
/>
</View>
),
})
注意这里的navigationBackGroundColor是一个字符串,类似’rgba(153,153,153,1)’,最后那个参数就是透明度。不用用opacity来设置透明,因为这个会连上面的子控件一起显示透明了。