ReactXP:构建跨平台应用程序
来自菜鸟教程
使用 React 构建跨平台应用程序并不是什么新鲜事。 今天,许多公司已经(并且仍在使用)React Native 用于移动优先项目。 ReactXP 试图通过跨多个平台重用视图层来进一步实现这一点,这是 React Native 无法实现的。
创建一个 ReactXP 项目
我们可以克隆包含各种示例的 GitHub 存储库,或者像这样全局安装 Create RX CLI:
$ npm install create-rx-app -g
要创建您的第一个 ReactXP 应用程序,请在安装 CLI 后运行以下命令:
$ create-rx-app HelloRX # OR $ npx create-rx-app HelloRX
如果我们调查 package.json 文件,我们可以了解如何启动/构建我们的项目,如 scripts 对象所示:
"scripts": {
"start:android": "yarn rn-cli run-android",
"start:windows": "yarn rn-cli run-windows",
"start:ios": "yarn rn-cli run-ios",
"start:web": "cross-env platform=web webpack-dev-server --config=web/webpack/dev.js --progress --colors --mode=development",
"start:rn-dev-server": "yarn rn-cli start --reset-cache",
"build:web": "cross-env platform=web webpack --config=web/webpack/prod.js --progress --colors --mode=production",
}
出于我们演示的目的,我将在 iOS 和 Web 上运行它。 您可以执行相同操作或选择您选择的其他平台。
$ npm run start:web $ npm run start:ios
你好,鳄鱼。
我们将创建一个示例应用程序,它使用 ReactXP 将来自 HTTP 服务器的 fetch 数据显示在屏幕上。 在 App.tsx 内部,添加以下代码:
import React from 'react';
import { Component, Styles, View, Text, ScrollView } from 'reactxp';
const _styles = {
main:
Styles.createViewStyle({
flex: 1,
}),
navBarText:
Styles.createTextStyle({
color: 'white',
}),
navBar:
Styles.createViewStyle({
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#0984e3',
height: 65,
}),
scroll:
Styles.createScrollViewStyle({
alignSelf: 'stretch',
backgroundColor: '#f5fcff',
padding: 16,
}),
user:
Styles.createTextStyle({
marginBottom: 10,
}),
};
export class App extends Component {
public state = {
users: [],
};
public async componentWillMount() {
const req = await fetch(`https://jsonplaceholder.typicode.com/users`);
const data = await req.json();
this.setState({
users: data,
});
}
public displayUsers = (users) => {
return users.map((user) => (
<View key={user.id} style={_styles.user}>
<Text>{user.name}</Text>
<Text>{user.email}</Text>
</View>
));
}
public render() {
return (
<View useSafeInsets={true} style={_styles.main}>
<View style={_styles.navBar}>
<Text style={_styles.navBarText}>Users</Text>
</View>
<ScrollView style={_styles.scroll}>{this.displayUsers(this.state.users)}</ScrollView>
</View>
);
}
}
从我们的 _styles 对象开始,为了在每个平台上定制样式,我们使用 createXStyle 将样式转换为每个独特的原生元素。 正如预期的那样,每个样式元素都必须匹配适当的标签 - 例如,createViewStyle 必须放在 View 元素上。
从这里开始的一切都类似于标准的 React/React Native 应用程序。 请注意在使用之前我们必须如何从 reactxp 导入每个组件。
这是我们最终的应用程序的样子:
您可以在此处 查看 ReactXP 内部组件的完整列表。