React-Native:子组件的条件样式

时间:2017-02-05 23:55:46

标签: react-native

我有一个数字1,2,3的数组。我正在尝试为每个数字映射它以呈现Square组件。这很好。现在我想根据值(1,2或3)有条件地设置Square组件的样式。我在'switch'(意外令牌)的行上有一个语法错误,我似乎无法找到原因。

class MainMaze extends Component {

  generateMaze() {
    const { tiles, cols, rows } = this.props.grid;
    return (
      tiles.map((sq, i) =>
        switch (sq) {
          case 3:
            return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>;
          case 2:
            return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>;
          default:
            return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>;
        }
    );
  }
  render() {
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {this.generateMaze()}
        </CardSection>
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    status: state.status,
    position: state.position,
    grid: state.grid
  };
};

export default connect(mapStateToProps)(MainMaze);

Square组件:

import React from 'react';
import { View, Text } from 'react-native';

const Square = (props) => {
  return (
    <View style={[styles.containerStyle, props.style]}>
      <Text>
        {props.children}
      </Text>
    </View>
  );
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderColor: '#ddd',
    elevation: 1,
    alignItems: 'center',
    justifyContent: 'center',
    margin: 0,
    height: 30,
    width: 30
  }
};

export { Square };

1 个答案:

答案 0 :(得分:1)

以下是具有多个语句的箭头表达式函数的正确语法(取自enter image description here):

(param1, param2, …, paramN) => { statements } 即,您应该使用switch包裹{...}块:

generateMaze() { const { tiles, cols, rows } = this.props.grid; return ( tiles.map((sq, i) => { switch (sq) { case 3: return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>; case 2: return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>; default: return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>; } } )) }