React 360 简介

React 360 (或React VR) 是一个用于创建与 React 的虚拟现实体验的库,并使用 Three.js进行渲染。

React 360的使用方式与React Native类似,它是一种使用自定义组件的库,而不与我们所知道的DOM进行交互。

如何安装 React 360 CLI

首先,请确保在您的计算机上安装了 Node.js

1$ npm install -g react-360-cli

我们现在将能够在我们的机器上在全球范围内使用react-360

创建一个新项目

使用 CLI,我们可以使用init命令创建一个新的项目:

1$ react-360 init hello-vr
2
3$ cd hello-vr
4
5$ code .
6
7$ npm run start

这将创建一个名为hello-vr的新目录,并在这个目录中运行npm run start,我们正在启动Metro包裹,我们的应用程序出现在 http://localhost:8081/index.html

Screenshot: our starting app

React 360(如其名称所示)被建造以与180-360度平方角的照片/视频工作,这方面的力量可以从开始项目中看到。

它也配备了多种内置的用户界面组件,我们可以使用这些组件的例子是: View, Image, Entity,和 VrButton

例子

让我们看看通过潜入client.js的方式来实现这一点:

 1import { ReactInstance } from 'react-360-web';
 2
 3function init (bundle, parent, options = {}) {
 4  const r360 = new ReactInstance(bundle, parent, {
 5    // Add custom options here
 6    fullScreen : true,
 7    ...options
 8  });
 9
10  // Render your app content to the default cylinder surface
11  r360.renderToSurface(
12    r360.createRoot(
13      'hello_vr',
14      {
15        /* initial props */
16      }
17    ),
18    r360.getDefaultSurface()
19  );
20
21  // Load the initial environment
22  r360.compositor.setBackground(r360.getAssetURL('360_world.jpg'));
23}
24
25window.React360 = { init };

我們將「r360.createRoot」的根設定為在「index.js」中找到的「hello_vr」反應組件,請注意它是如何用字符串名稱引用的。

我们可以通过使用VrButton组件与环境进行交互:

 1import React from 'react';
 2import { AppRegistry, StyleSheet, Text, View, VrButton } from 'react-360';
 3
 4export default class hello_vr extends React.Component {
 5  state = {
 6    counter : 0
 7  };
 8
 9  _incrementCounter = () => {
10    this.setState({
11      counter : (this.state.counter += 1)
12    });
13  };
14
15  render () {
16    return (
17      <View style={styles.panel}>
18        <View style={styles.greetingBox}>
19          <VrButton onClick={this._incrementCounter}>
20            <Text style={styles.greeting}>You've clicked me {this.state.counter} times.</Text>
21          </VrButton>
22        </View>
23      </View>
24    );
25  }
26}
27
28const styles = StyleSheet.create({
29  panel       : {
30    // Fill the entire surface
31    width           : 1000,
32    height          : 600,
33    backgroundColor : 'rgba(255, 255, 255, 0.4)',
34    justifyContent  : 'center',
35    alignItems      : 'center'
36  },
37  greetingBox : {
38    padding         : 20,
39    backgroundColor : '#000000',
40    borderColor     : '#639dda',
41    borderWidth     : 2
42  },
43  greeting    : {
44    fontSize : 30
45  }
46});
47
48AppRegistry.registerComponent('hello_vr', () => hello_vr);

每次我们点击按钮,我们的计数增加:

Screenshot: counter increased

生产

要为我们的 React 360 项目生成生产构建,请在您的终端中运行以下操作:

1$ npm run bundle

然后,您应该能够访问您新建的生产文件在 ./build

Published At
Categories with 技术
Tagged with
comments powered by Disqus