从父组件(props)设置样式,并从组件本身进行本机反应

时间:2019-04-16 00:04:11

标签: javascript reactjs styles native

是否可以将父级的某些样式属性设置为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;

这是我的父母:

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'}
    />
    );
  }
};

});

我只想设置父级的backgroundColor。

2 个答案:

答案 0 :(得分:1)

尝试类似

首先从父对象发送样式作为对象... ex ..

style={color:"#abcd"}

然后在子组件内部。将其添加到样式数组

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

答案 1 :(得分:1)

好的,我找到了解决方案。 在父项上:

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',
}
};