[react-native] 01 项目创建 + stylesheet

93 阅读2分钟

前言

从零开始学习React Native开发,使用函数式组件的写法。

项目创建

环境搭建

首先,你需要在电脑上安装好Node.js和npm。然后,使用npm安装React Native的命令行工具:

npm install -g react-native-cli

创建项目

接着,创建一个新的React Native项目:

react-native init MyProject

启动程序

进入项目文件夹,并启动React Native应用程序:

cd MyProject

react-native start

运行模拟器

在另一个终端窗口中,运行以下命令来启动应用程序:

react-native run-android

或者

react-native run-ios

这样,你就可以在模拟器或真机上看到一个简单的React Native应用程序了。

image.png

创建组件

在项目中创建一个新的文件夹,例如“components”,用于存放你的组件。接着,在该文件夹中创建一个新的文件,例如“MyComponent.js”,用于编写你的第一个React Native组件。

image.png

在该文件中,编写以下代码:

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

const MyComponent = (props) => {
  return (
    <View>
      <Text>Hello {props.name}!</Text>
    </View>
  );
}

export default MyComponent;

这是一个基本的函数式组件,它接受一个名为“name”的属性,并将其显示在屏幕上。

调用组件

在应用程序中使用组件 在应用程序的主文件中,例如“App.js”,引入你的组件:

import React from 'react';
import { View } from 'react-native';
import MyComponent from './components/MyComponent';

const App = () => {
  return (
    <View>
      <MyComponent name="React Native" />
    </View>
  );
}

export default App;

这个文件中,我们引入了刚才创建的组件,并将其放置在一个View组件中。我们还向组件传递了一个名为“name”的属性,值为“React Native”。

运行应用程序

最后,运行应用程序,查看你的组件是否正常工作:

react-native run-android

或者

react-native run-ios

你应该能够在模拟器或真机上看到一个显示“Hello React Native!”的屏幕。

这就是使用函数式组件在React Native中创建和使用组件的基本步骤。你可以继续学习更高级的React Native功能,例如导航、网络请求、状态管理等。

更改样式

第一种方法 标签修改

<View>  
    <Text style={{fontSize:20, color:'red'}}>Hello {props.name}!</Text>  
</View>

第二种方法 创建样式属性

**import React from 'react';  
import { Text, View, StyleSheet } from 'react-native';  
  
const DemoComponent = (props) => {  
    return (  
        <View>  
            <Text style={styles.h1}>Hello {props.name}!</Text>  
        </View>  
    );  
}  
  
export default DemoComponent;  
  
const styles = StyleSheet.create({  
    h1:{  
        fontSize:40,  
        fontWeight:'bold'  
        },  
    h2:{  
        fontSize:30,  
        fontWeight:'bold',  
        color:'blue'  
    }  
})**

image.png

如果把 h1 改成 h2 样式,我们来看一下区别

<View>  
    <Text style={styles.h2}>Hello {props.name}!</Text>  
</View>

image.png