React Native中使用map生成的单个元素如何自定义样式
解决方案
直接调整按钮组件的传参逻辑和渲染逻辑即可,不需要推翻现有代码结构,具体操作步骤如下:
步骤1:改造通用InputButton组件,支持自定义样式透传
修改你的按钮组件,让它可以接收外部传入的样式,和默认样式合并生效:
import React from "react"; import { StyleSheet, Text, TouchableOpacity } from "react-native"; export default class InputButton extends React.Component{ render() { const {value, handleOnPress, style, textStyle} = this.props; return ( <TouchableOpacity // 数组格式的style会自动合并,后传入的样式优先级更高 style={[styles.container, style]} onPress={()=> handleOnPress(value)}> <Text style={[styles.text, textStyle]}>{value}</Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ container:{ flex:1, margin: 1, backgroundColor: 'black', justifyContent:"center", alignItems: 'center' }, text:{ fontSize: 30, color: 'white', fontWeight: 'bold' } });
步骤2:选择适配的自定义样式方案
方案A:通过按钮值匹配样式(改动最小,适合少量按钮自定义场景)
不需要修改现有的按钮配置数组,额外加一个样式映射表即可:
// 新增样式映射,key对应按钮value,值为要覆盖的样式 const buttonStyleMap = { 'AC': {backgroundColor: '#ff3b30'}, 'DEL': {backgroundColor: '#ff9500'}, '=': {backgroundColor: '#4cd964'}, '/': {color: '#ff9500'}, '*': {color: '#ff9500'}, '+': {color: '#ff9500'}, '-': {color: '#ff9500'}, }
然后修改renderButtons中渲染InputButton的部分,传入匹配到的样式:
return <InputButton value={buttonItems} handleOnPress={handleInput.bind(buttonItems)} style={buttonStyleMap[buttonItems] || {}} key={'btn-'+ buttonIndex}/>
方案B:修改按钮配置数组结构(适合需要大量自定义属性的场景)
如果后续还要给按钮加专属属性(比如不同的点击逻辑、flex占比等),可以把数组项从字符串改成对象格式:
const buttons = [ [{value: 'AC', style: {backgroundColor: '#ff3b30'}}, {value: 'DEL', style: {backgroundColor: '#ff9500'}}], ['7','8','9', {value: '/', textStyle: {color: '#ff9500'}}], ['4','5','6', {value: '-', textStyle: {color: '#ff9500'}}], ['1','2','3', {value: '*', textStyle: {color: '#ff9500'}}], ['0','.', {value: '=', style: {backgroundColor: '#4cd964'}}, {value: '+', textStyle: {color: '#ff9500'}}] ]; // 横竖屏的buttons_landscape数组同理修改
对应修改渲染逻辑,兼容字符串和对象两种格式:
let rowItem = buttonRows.map((buttonItem,buttonIndex)=>{ // 判断项是字符串还是对象 const btnProps = typeof buttonItem === 'string' ? {value: buttonItem} : buttonItem; return <InputButton {...btnProps} handleOnPress={handleInput.bind(btnProps.value)} key={'btn-'+ buttonIndex}/> });
内容的提问来源于stack exchange,提问作者m3k_1
相关产品推荐
相关产品推荐

