Aframe 注销组件

Jor*_*leo 6 reactjs aframe

我正在学习如何使用 React 和 Redux 构建框架。我正在创建自定义组件并将它们注册到我的reactjs componentWillMount 生命周期事件中。例如:我将光线投射的结果发送到父级 React 组件,以保存用于其他目的。这很好用。

import React, {Component, PropTypes} from 'react'

export default class AframeComponent extends Component {
  static propTypes = {
    cb: PropTypes.func.isRequired
  }

  componentWillMount () {
    const {AFRAME} = window
    const aframeComponent = this

    if (!AFRAME) return

    if (!AFRAME.components['sphere-listener']) {
      AFRAME.registerComponent('sphere-listener', {
        init () {
          const {el} = this
          el.addEventListener('mouseup', (evt) => {
            const camera = document.querySelector('#camera')
            aframeComponent.handleRaycast(evt.detail.intersection.point, camera.components.rotation)
          })
        }
      })
    }
  }

  handleRaycast (position, rotation) {
    const {cb} = this.props

    /* do cool stuff here with the position and rotation */

    this.setState({position, rotation}, () => {
      cb(position, rotation)
    })
  }

  render () {
    return (
      <a-scene>
        <a-sphere radius="30" sphere-listener />
        <a-entity id="camera" look-controls mouse-cursor>
          <a-cursor fuse="true" color="yellow" />
        </a-entity>
        {/* cool stuff happens here */}
      </a-scene>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

当我使用 aframe 卸载 React 组件并稍后在应用程序使用中重新安装时,我遇到了问题。我收到错误,但它们是有道理的。我正在注册 AFRAME 的组件正在查找对特定实例的对象引用,AframeComponent该实例在第二次加载组件时不再存在。

我还没有找到正式注销组件的方法。我已经能够让它工作了,但感觉很糟糕。在我的组件将卸载中,我可以手动删除组件,然后允许它们重新注册。delete AFRAME.components['sphere-listener']

问题:

  1. 有没有办法 AFRAME.unregisterComponent() ?
  2. 我是否只是错误地构建了组件,因为它们具有状态依赖性?我开始认为他们应该是无国籍的。
  3. 如果是这样,我如何将函数从反应类传递到模式中?像这样: <a-sphere radius="30" sphere-listener={cb: ${() => { console.log('call back') }}} />

谢谢,

约旦

ngo*_*vin 5

组件应该在全局级别注册,而不是在运行时注册。您不应该像 DOM 元素那样注册和取消注册组件,因为没有太多好处。但如果你必须这样做:delete AFRAME.components['sphere-listener']. 编辑:我确实看到您正在尝试将 React 变量关闭到组件中。注册/注销有点有效,但我建议将它们解耦。

如果需要将数据传递到组件中,可以使用schema, 并通过模式绑定数据(例如,somecomponent={{foo: this.state.blah}})。

你不能传递函数。您应该使用事件侦听器进行通信<Entity events={{collide: () => {}}>,并且可以在 A 框架级别发出事件。

重要的是要区分应该在 A-Frame 组件(3D、VR、事件)中执行哪些操作以及应该在 React 级别(视图层、数据绑定)执行哪些操作。