2017-02-05 79 views
1

我有一个数组,其中包含数字1,2,3。我试图为每个数字映射它以呈现Square组件。这工作得很好。现在我想根据值(1,2或3)有条件地设置Square组件的样式。我在'switch'(意外的标记)上出现语法错误,我似乎无法找到原因。React-Native:子组件的条件样式

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); 

广场组分:

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 }; 
+0

你能从'Square'组件中使用道具吗?我的意思是'Square'组件中有什么道具。 –

回答

1

这里是与多个语句的箭头表达功能的正确的语法(从mozilla docs截取):

(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>; } } )) }

+0

谢谢。 ))之后还需要一个分号)但是就是这样。 – Wasteland