在React Native中样式化自定义组件

时间:2019-04-15 09:33:06

标签: react-native

我试图在react native中为我的自定义组件添加样式,但是无论我做什么,样式都无效。这是我的代码:

// App.js
import MyCustomComponent from './components/myCustomComponent.js';

render() {
  return (
    <View style={styles.container}>
      <MyCustomComponent style={{marginTop: 10}}/>
    </View>
  );
}

项目可以正常编译,并且我的自定义组件可以在屏幕上正常显示,但是没有应用marginTop样式。值得注意的是,父View组件的样式确实适用。这是我今天刚刚创建的一个全新项目。这似乎应该是非常基础的,但是却无法正常工作。我该怎么做才能应用这种样式?

自定义组件代码:

import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, View, Button} from 'react-native';

type Props = {};
export default class MyCustomComponent extends Component<Props> {

  render() {
    return (
      <View style={styles.container}>
        <Image
          source={{ uri: "source here" }}
          style={{ width: 50, height: 50 }}
         />
         <TextInput
          style={{ height: 50 }}
          placeholder="Search"
        />
      </View>
    )
  }
}

5 个答案:

答案 0 :(得分:3)

您可以使用以下代码:

export default class MyCustomComponent extends Component<Props> {
  render() {
    return (
      <View style={[styles.container, {...this.props.style}]}>
        ...
      </View>
    )
  }
}

现在,将应用styles.container,并且通过style传递给组件的所有内容都会添加到组件样式中。

我希望这可以为您提供帮助

答案 1 :(得分:1)

您可以通过将样式作为道具来将样式应用于自定义组件。

在MyCustomComponent中将其用作style={this.props.style}

import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, View, Button} from 'react-native';

type Props = {};
export default class MyCustomComponent extends Component<Props> {

  render() {
    return (
      <View style={[styles.container,{this.props.style}]}>//<--Use like this---
        <Image
          source={{ uri: "source here" }}
          style={{ width: 50, height: 50 }}
         />
         <TextInput
          style={{ height: 50 }}
          placeholder="Search"
        />
      </View>
    )
  }
}

答案 2 :(得分:1)

将此代码添加到您的 CustomText.js 文件(自定义组件)中:

import React from 'react'
import {Text, StyleSheet} from 'react-native'

const CustomText = props => {
    return (<Text {...props} style={{...styles.text, ...props.style}}>{props.children}</Text>);
}

export default CustomText;

const styles = StyleSheet.create({
    text:{
        color: '#000'
    }
})

并在文件中使用:

<CustomText style={styles.text}>My text</CustomText>

const styles = StyleSheet.create({
    text:{
        fontSize: 20,
    }
});

此代码 merge 设置样式并将所有属性传递给自定义组件。

答案 3 :(得分:0)

例如,让我们更改自定义卡片的背景颜色。 自定义卡:

export default function MyCard({color}) {
    return (
         <View style={[styles.card, {backgroundColor: color}]}>
        </View>
    )
}

在另一个文件中

<MyCard color={"pink"} />

在这里,styles.card是在“自定义卡片”文件中添加的样式,颜色是在组件使用期间给出的。 注意:MyCard( {颜色} )如果错过添加突出显示括号的功能,则将无法使用。我遇到了这个问题。

答案 4 :(得分:-1)

您需要在MyCystomComponent内部自己应用此样式。例如:

const MyCustomComponent = ({style}) => (
  <View style={style}> // This will be the style that is passed as a prop.
  </View>
);