【问题标题】:How can I concatenate an array index to change the style of a component depending on the index?如何连接数组索引以根据索引更改组件的样式?
【发布时间】:2019-02-12 07:54:45
【问题描述】:

我正在使用 React Native 来执行此操作。我有这些样式:

const styles = StyleSheet.create({
  tabStyle: {
    marginHorizontal: 10,
    marginTop: 20,
    borderRadius: 2,
  },
  tabStyle_0: {
    backgroundColor: '#ff5252',
  },
  tabStyle_1: {
    backgroundColor: '#3da7dc',
  },
});

我有这个功能:

renderTabBar = props => (
    <View style={styles.tabBar}>
      {props.navigationState.routes.map((route, i) => {
        return (
          <TouchableOpacity
            key={route.key}
            // HERE IS WHERE I NEED TO APPLY THE FUNCIONALITY
            style={[styles.tabStyle, styles.tabStyle_`${i}`]}
            onPress={() => this.setState({ index: i })}
          >
            <Animated.Text style={{ color: '#ffffff' }}>
              {route.title}
            </Animated.Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );

看到我正在这样做: style={[styles.tabStyle, styles.tabStyle_${i}]}

但它根本不起作用。我收到此错误

TypeError: TypeError: styles.tabStyle_ 不是函数

所以我只需要将TouchableOpacity 的样式设置为styles.tabStyle_0styles.tabStyle_1styles.tabStyle_2

在这种情况下,我怎样才能实现我所需要的?

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    使用变量作为属性访问器时,需要使用bracket notation

    改一下就行了

    style={[styles.tabStyle, styles.tabStyle_${i}]}
    

    到这里

    style={[styles.tabStyle, styles[`tabStyle_${i}`]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 2021-06-28
      • 2020-03-20
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多