React Native 如何将组件内的backgroundColor传递给外部样式文件使用
问题原因&修复方案
你代码有两个核心问题:
- React Native 官方提供的
StyleSheet.create()仅支持静态样式配置,不接受函数作为属性值,你写的动态样式函数不能放在StyleSheet.create中定义。 - 业务逻辑存在三处疏漏:
- 列表渲染函数
renderItem没有返回值,无法渲染子项 - 调用
Item组件时没有传递backgroundColor属性 Item组件内调用样式时错误引用了不存在的DATA.backgroundColora变量,应该使用组件接收的backgroundColor参数
- 列表渲染函数
修改后代码
styles.js
import {StyleSheet} from 'react-native'; // 动态item样式单独导出 export const getItemStyle = (bgColor) => ({ margin: 8, width: 300, height: 200, borderRadius: 20, justifyContent: 'center', alignItems: 'center', backgroundColor: bgColor }) // 静态样式统一用StyleSheet管理 const styles = StyleSheet.create({ container: { flex: 1 }, title: { fontSize: 32, } }) export default styles;
Carts.js
import {View, Text, FlatList} from 'react-native'; // 导入静态样式和动态样式方法 import styles, { getItemStyle } from './styles'; const DATA = [ { id: '1', title: 'First Item', backgroundColor: "#ffcc66", }, { id: '2', title: 'Second Item', backgroundColor: "#ffb3b3", }, { id: '3', title: 'Third Item', backgroundColor: "#b3d9ff", } ]; const Item = ({ title, backgroundColor }) => ( <View style={getItemStyle(backgroundColor)}> <Text style={styles.title}>{title}</Text> </View> ); function Carts() { const renderItem = ({ item }) => { // 补全return,传入backgroundColor参数 return <Item title={item.title} backgroundColor={item.backgroundColor} /> } return ( <View style={styles.container}> <FlatList horizontal={true} showsHorizontalScrollIndicator={false} data={DATA} renderItem={renderItem} keyExtractor={item => item.id} /> </View> ); }; export default Carts;
内容的提问来源于stack exchange,提问作者Ali Mahmoudi
相关产品推荐
相关产品推荐

