react native中的动态自定义按钮



我正试图通过传递"PRIMARY";或";第三;以键入。我认为";styles['container_${type}']"在第7行,但我记不清

import { View, StyleSheet, Image ,Text, Pressable} from 'react-native';
function CustomButton({onPress, text, type}) {        
return (           
<Pressable                                                    
onPress={onPress}            
style={[styles.container, styles['container_${type}']]}>             
<Text  style={[styles.text, styles['text_${type}']]} >{text}</Text>            
</Pressable>
);            
}    
const styles = StyleSheet.create({
container:{

width: '100%',
padding: 15,
alignItems: 'center',
borderRadius: 30,
marginVertical: 25,
},
container_PRIMARY:{
backgroundColor: '#fde17d',
},
container_TERTIARY:{
backgroundColor: 'pink',
},
text: {
fontWeight: 'bold',
color: 'white',
},
text_TERTIARY :{
color: 'gray',
}
})
export default CustomButton; 

试试这个,

import { View, StyleSheet, Image ,Text, Pressable} from 'react-native';
function CustomButton({onPress, text, type}) {   
const stylesheet = type == 'PRIMARY' ? 'container_PRIMARY' : 'container_TERNIARY';    
return (           
<Pressable                                                    
onPress={onPress}            
style={[styles.container, {...stylesheet}]}>             
<Text  style={[styles.text, styles['text_${type}']]} >{text}</Text>            
</Pressable>
);            
}    
const styles = StyleSheet.create({
container:{

width: '100%',
padding: 15,
alignItems: 'center',
borderRadius: 30,
marginVertical: 25,
},
container_PRIMARY:{
backgroundColor: '#fde17d',
},
container_TERTIARY:{
backgroundColor: 'pink',
},
text: {
fontWeight: 'bold',
color: 'white',
},
text_TERTIARY :{
color: 'gray',
}
})
export default CustomButton; 

使用``用于模板文字,而不是"。

最新更新