问题
I am making a react-native app that has a custom view like a grid view. All the cells of the view have same size except one. I want to give condition for the cell to have double the size from others.
I am making the view through an array using map function. Map function is not taking if statement. How should I use it?
// Buttons Array
buttons = [['1', '2', '3'],
['a', 'b', 'c'],
['q', 'w', 'e'],
['+', '-', '*'],
]
// '-' has double size...
import React, { Component } from 'react';
import {
View,
Text,
TouchableNativeFeedback
} from 'react-native';
//Styles
import styles from './styles';
export default class NumberButtons extends Component {
//This will call the bound function from its parent component
//to handle button press action/event
_handleOnPress = (value) => {
requestAnimationFrame(() => {
this.props.onBtnPress(value);
});
}
render() {
return (
<View style={styles.container}>
{
this.props.buttons.map((row, index) => (
<View key={index} style={styles.contRow}>
{
row.map((col,index) => (
//**** Here I want to use if else for row and column ***//
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={styles.text}>{col}</Text>
</View>
</TouchableNativeFeedback>
))
}
</View>
))
}
</View>
);
}
}
回答1:
You can render conditional views like this
<View style={styles.container}>
{this.state.buttons.map((row, index) => {
const myRow = row
console.log("myRow",myRow)
return (
<View key={index} style={styles.contRow}>
{
row.map((col,index) => {
if(col != 3 && myRow != null ){
return (
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={styles.text}>{col}</Text>
</View>
</TouchableNativeFeedback>
)
}
else {
return (
<TouchableNativeFeedback
key={index}
onPress={() => this._handleOnPress(col)}
background={TouchableNativeFeedback.SelectableBackground()}>
<View style={styles.buttonContainer}>
<Text style={{backgroundColor:'#78909C'}}>{col}</Text>
</View>
</TouchableNativeFeedback>
)
}
})
}
</View>
)})
}
</View>
回答2:
Here is the sample code how you can insert if and else in the nested map function.
this.props.availableEvents.map((item, i) => {
if (i < this.state.imageIndex) {
return null
} else if (i === this.state.imageIndex) {
return (
<Animated.View
{...this.imagePanResponder.panHandlers}
key={i}
style={[this.rotateAndTranslate, styles.cardContainer]}
>
<View style={{ width: '100%', height: '100%' }}>
</View>
</Animated.View>
)
} else {
return (
<Animated.View
key={i}
style={styles.cardContainer}>
<View style={{ width: '100%', height: '100%' }}>
</View>
</Animated.View>
)
}
}).reverse();
};
来源:https://stackoverflow.com/questions/54605677/how-to-use-if-else-condition-inside-nested-map-function-in-react-native