首页 > 解决方案 > 如何将值作为道具传递并以 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;

在这种情况下插入自定义弹性值的最佳方法是什么?

标签: reactjsreact-nativeimmutabilityreact-props

解决方案


你可以按照以下方式进行

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;

推荐阅读