2017-02-05 78 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