2017-04-19 97 views
1

我正在学习如何使用react和redux进行框架化。我正在创建自定义组件并在我的reactjs componentWillMount生命周期事件中注册它们。例如:我将我的光线投射的结果发送给父反应组件,以便保存用于其他目的。这很好。Aframe取消注册组件

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> 
 
    ) 
 
    } 
 
}

我现在遇到的问题时,我卸载与AFRAME的反应组件和应用程序使用后重新安装。我得到的错误,但他们是有道理的。我正在注册一个AFRAME的组件正在寻找一个对象引用,指向第二次加载组件时不再存在的特定实例AframeComponent

我还没有找到正式取消注册组件的方法。我已经能够使它工作,但感觉很不舒服。在我的组件将卸载我可以手动删除组件,然后让他们重新注册。 delete AFRAME.components['sphere-listener']

问题:

  1. 有没有办法来AFRAME.unregisterComponent()?
  2. 我只是构建组件不正确,因为他们有一个状态依赖?我开始认为他们应该是无国籍的。
  3. 如果是这样,我如何将一个反应类的函数传递给模式?像这样的:<a-sphere radius="30" sphere-listener={ CB:$ {()=> {执行console.log( '回调')}} } />

感谢,

乔丹

回答

1

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

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

您无法传递函数。您应该使用事件侦听器来沟通<Entity events={{collide:() => {}}>,并且您可以在A帧级别发出事件。

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

+0

感谢您的快速回复!我试图改变这些变化。 –