reactjs - 如何将值作为道具传递并以 CSS 样式(React Native)插入组件?
问题描述
我有一个可重用的功能组件,名为CardSection
. 我想为不同的 CardSection 组件传递使用不同的 flex 值。
因此,我想将 flex 的值作为道具传递给 CardSection 组件。例如:
<CardSection flex='1' />
<CardSection flex='3' />
但是,如果我尝试将 flex 的键值对添加到我的样式对象中,我会收到错误消息,因为我试图flex
在一个不可变的对象上设置一个带有值的键:
import React from 'react';
import { View } from 'react-native';
const CardSection = props => {
styles.container.flex = props.flex; // <---- Causes mutation error
return (
<View style={styles.container}>
{props.children}
</View>
);
};
const styles = {
container: {
borderBottomWidth: 1,
padding: 5,
backgroundColor: '#fff',
justifyContent: 'space-between',
borderColor: '#ddd',
position: 'relative',
borderWidth: 2,
borderColor: 'red',
}
};
export default CardSection;
在这种情况下插入自定义弹性值的最佳方法是什么?
解决方案
你可以按照以下方式进行
import React from "react";
import { View, StyleSheet } from "react-native";
class Main extends React.Component {
static getCardStyle(flexValue) {
return StyleSheet.create({
container: {
flex: flexValue,
borderBottomWidth: 1,
padding: 5,
backgroundColor: "#fff",
justifyContent: "space-between",
borderColor: "#ddd",
position: "relative",
borderWidth: 2,
borderColor: "red"
}
});
}
render() {
return <View style={getCardStyle(this.props.flex).container}>{props.children}</View>;
}
}
export default Main;
另一种最佳方式:
import React from 'react';
import { View } from 'react-native';
const CardSection = props => {
return (
<View style={styles.container(props.flex)}>
{props.children}
</View>
);
};
const styles = {
container: (flexValue) => { return {
borderBottomWidth: 1,
padding: 5,
flex:flexValue
backgroundColor: '#fff',
justifyContent: 'space-between',
borderColor: '#ddd',
position: 'relative',
borderWidth: 2,
borderColor: 'red',
}}
};
export default CardSection;
推荐阅读
- javascript - WebBrowser 控件阻止导航下一个 URL
- tableau-api - 如何在安装 Tableau 时纠正错误?
- java - Java 发送 Outlook 会议请求 ical4j
- php - 通过 PHP 将数据插入 mySQL 数据库不起作用
- ssis - SSIS 动态表和数据流中的列数
- c# - 如何使用 asp.net 在 Chrome 中删除或过期 cookie
- python - 无法访问 Python 2d 数组中的行元素?
- isabelle - 如何对不同模式的归纳谓词使用不同的代码引理?
- google-apps-script - 如何循环遍历问题选项,以便我可以将一个选项指定为正确,而将其他选项指定为不正确?
- ms-access - 微软访问?显示空白返回的通配符