基于状态

时间:2017-03-15 10:48:39

标签: react-native state

我正在尝试在我的React Native项目中添加一些动态样式。 我正在使用React Native Snackbar,但此时它会在我的浮动操作按钮前面。这不是材料设计的设计规则。

出于这个原因,我需要在快餐栏处于活动状态时移动我的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,
    },
});

但我不喜欢这个解决方案,因为我得到了两个样式表

1 个答案:

答案 0 :(得分:4)

您不需要拥有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,
  },
})