从 parent 组件(道具)和组件本身设置样式反应本机

Set styling from parent component (props) and from component itself react native

是否可以将 parent 的一些样式属性设置为 props 和组件本身的一些样式属性?

这是我的组件:

import React,{ Component } from 'react';
import { View, Text } from 'react-native';

class BackgroundMar extends Component {

render(){
    return (
        <View style={[styles.viewStyle]}>
            <Text>{this.props.test}</Text>
        </View>
    )
    }
};

var styles = {
viewStyle: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: props.color
}
};

export default BackgroundMar;

这是我的 parent:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import BackgroundMar from "./components/BackgroundMar";

export default class App extends React.Component {
  render() {
    return (
    <BackgroundMar
        test={'aaa'}
        color={'#ff2044'}
    />
    );
  }
};

});

我只想设置 parent 的 backgroundColor。

试试

首先从父级发送样式作为对象...例如 ..

style={{color:"#abcd"}}

然后在子组件里面。将其添加到样式数组

<View style={this.props.style ? [styles.viewStyle, this.props.style] : 
  [styles.viewStyle]}>

好的,我找到了解决方案。 在 parent:

export default class App extends React.Component {
render() {
return (
    <BackgroundMar
        test={'#52a03f'}
    />
);
}
};

关于组件本身:

class BackgroundMar extends Component {

render(){
    return (
        <View style={[styles.viewStyle, { backgroundColor: this.props.test}]}>
            <Text>{this.props.test}</Text>
        </View>
    )
}
};

var styles = {
viewStyle: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
}
};