我试图在我的React Native项目中添加一些动态样式。我正在使用React Native Snackbar,但是现在它在我的Floating Action Button前面。这不是材料设计的设计规则。
因此,每当小吃店处于活动状态时,我都需要移动FAB。我将其保持在某种状态,但是我需要基于该状态的样式。
这时我得到以下代码:
constructor(props){
super(props);
this.state = {
snackbar: true,
}
}
../
const styles = StyleSheet.create({
container: {
marginBottom: this.state.snackbar ? 50 : 0,
backgroundColor: colors.accentColor,
height: Dimensions.get('window').width / 9,
width: Dimensions.get('window').width / 9,
},
});
我得到的错误是它对象未定义。所以我不确定为什么这不起作用。也许有人可以帮助我解决这个问题。
此时,我通过以下方式解决了问题:
constructor(props){
super(props);
this.state = {
snackbar: true,
}
Snackbar.addEventListener('show',()=>{this.setState({snackbar:true})})
Snackbar.addEventListener('hidden',()=>{this.setState({snackbar:false})})
}
render() {
return <ActionButton
onPress={() => {this.props.nav.push(routes.takePicture)}}
style={this.state.snackbar ? stylesFabUp : styles}
/>;
}
}
const stylesFabUp = StyleSheet.create({
container: {
marginBottom: 40,
backgroundColor: colors.accentColor,
height: Dimensions.get('window').width / 9,
width: Dimensions.get('window').width / 9,
},
})
const styles = StyleSheet.create({
container: {
// marginBottom: this.state.snackbar ? 50 : 0,
backgroundColor: colors.accentColor,
height: Dimensions.get('window').width / 9,
width: Dimensions.get('window').width / 9,
},
});
但是我不喜欢这种解决方案,因为我没有2个样式表
您不需要2个样式表。
考虑以下代码:
constructor(props){
super(props);
this.state = {
snackbar: true,
}
Snackbar.addEventListener('show', () => {this.setState({snackbar:true})})
Snackbar.addEventListener('hidden', () => {this.setState({snackbar:false})})
}
render() {
const fabPositionStyle = this.state.snackbar ? styles.pushUp : styles.normal
return <ActionButton
onPress={() => {this.props.nav.push(routes.takePicture)}}
style={[ styles.fab, fabPositionStyle ]}
/>;
}
}
const styles = StyleSheet.create({
fab: {
height: Dimensions.get('window').width / 9,
width: Dimensions.get('window').width / 9,
backgroundColor: colors.accentColor,
},
pushUp: {
marginBottom: 40,
},
normal: {
marginBottom: 0,
},
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句