React Native 的开发使用的是JavaScript, 但语法与JavaScript 又有一些不同,是基于JavaScript 的一种语法扩展,名为 JSX。下面来看一下 JSX 的相关特点:
类似于html标签的格式
JSX需要有一个根节点<> xxx </>,一般使用<View> </View> 作为根节点- 单标签是需要封闭的
<Image>—><Image />
组件化开发
React Native使用组件化开发的方式来构建应用程序,JSX支持class、function 两种方式声明组件
-
使用
class声明组件(比较古老, 不推荐)通过继承
React.Component可以创建class组件import React from "react"; import { Text, View } from "react-native"; class ClassView extends React.Component { // 构造函数 constructor(props) { super(props); } // 渲染函数 render() { return ( <View style=> <Text style=> {`name=${name}, age=${age}, level=${level}, sex=${sex}`} </Text> <Text style=> {`${address}`} </Text> </View> ); } } export default ClassView; -
使用
function声明组件(简洁方便,推荐)函数组件有多种写法,一般使用极简写法,直接导出组件
export default (parameters) => {}export default (props) => { return ( <View> <Text style={[styles.txt, styles.txtBold]}> {`Hi`} </Text> </View> ); }
与JavaScript紧密集成
JSX语法与JavaScript紧密集成,这意味着您可以在JSX标记中使用JavaScript表达式和逻辑
import React from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => (
<View>
{/* JavaScript expression */}
{this.state.isLoading ? <Text>Loading...</Text> : null}
</View>
);
export default MyComponent;
支持自定义属性
JSX语法支持自定义属性,这使得您可以更灵活地描述组件
import React from 'react';
import { View, Text } from 'react-native';
const MyComponent = () => (
<View customAttribute="myCustomValue">Hello World!</View>
);
export default MyComponent;
支持嵌套
JSX语法支持嵌套组件,这使得您可以更轻松地组织复杂的UI
import React from 'react';
import { View, Text } from 'react-native';
import MyNestedComponent from './MyNestedComponent';
const MyComponent = () => (
<View>
{/* Parent component */}
<MyNestedComponent />
{/* Another child component */}
</View>
);
export default MyComponent;