微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用reactnative向您的应用程序添加样式或CSS?

可以按如下方式设置应用程序的样式 -

  • 使用样式表组件
  • 使用内联样式

使用样式表组件

当您想要将样式应用到应用程序时,React 原生样式表组件非常方便且简洁。要使用样式表组件,首先将其导入,如下所示 -

import { StyleSheet } from 'react-native';

您可以使用样式表组件创建样式,如下所示 -

const styles = StyleSheet.create({
   container: {
      flex: 1,
      marginTop: StatusBar.currentHeight || 0,
   },
   item: {
      margin: 10,
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
   }
});

上面的样式可以在你的代码中使用如下 -

<View style={styles.container}></View>

这里是一个使用样式表来显示 FlatList 组件的示例 -

示例 1

import React from "react";
import { FlatList , Text, View, StyleSheet, StatusBar } from "react-native";
export default class App extends React.Component {
   constructor() {
      super();
      this.state = {
         data: [
            { name: "Javascript Frameworks", isTitle: true },
            { name: "Angular", isTitle: false },
            { name: "ReactJS", isTitle: false },
            { name: "VueJS", isTitle: false },
            { name: "ReactNative", isTitle: false },
            { name: "PHP Frameworks", isTitle: true },
            { name: "Laravel", isTitle: false },
            { name: "CodeIgniter", isTitle: false },
            { name: "CakePHP", isTitle: false },
            { name: "Symfony", isTitle: false }
         ],
         stickyHeaderIndices: []
      };
   }
   renderItem = ({ item }) => {
      return (
         <View style={styles.item}>
            <Text style={{ fontWeight: (item.isTitle) ? "bold" : "", color: (item.isTitle) ? "red" : "gray"}} >
               {item.name}
            </Text>
         </View>
      );
   };
   render() {
      return (
         <View style={styles.container}>
            <FlatList
               data={this.state.data}
               renderItem={this.renderItem}
               keyExtractor={item => item.name}
               stickyHeaderIndices={this.state.stickyHeaderIndices}
            />
         </View>
      );
   }
}
const styles = StyleSheet.create({
   container: {
      flex: 1,
      marginTop: StatusBar.currentHeight || 0,
   },
   item: {
      margin: 10,
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
   }
});

输出

如何使用reactnative向您的应用程序添加样式或CSS?

使用内联样式

您可以使用 style 属性添加内联样式。然而,这不是最佳实践,因为它可能很难阅读代码。这是一个关于如何在reactnative组件中使用内联样式的工作示例

示例2

导出认应用程序;

import React from 'react';
import { Button, View, Alert } from 'react-native';

const App = () => {
   return (
      <View style={{flex :1, justifyContent: 'center', margin: 15 }}>
         <Button
            title="Click Me"
            color="#9C27B0"
            onPress={() => Alert.alert('Testing Button for React Native ')}
         />
      </View>
   );
}

输出

如何使用reactnative向您的应用程序添加样式或CSS?

以上就是如何使用reactnative向您的应用程序添加样式或CSS?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐