我正在学习如何使用react和redux进行格式化 . 我正在创建自定义组件并在reactjs componentWillMount生命周期事件中注册它们 . 例如:我将我的光线投射结果发送到父反应组件,以便将其保存用于其他目的 . 这很好用 .
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的组件正在寻找对第二次加载组件时不再存在的 AframeComponent
特定实例的对象引用 .
我还没有找到正式取消注册组件的方法 . 我已经能够使它工作,但它感觉hacky . 在我的组件将卸载我可以手动删除组件然后允许它们重新注册 . delete AFRAME.components['sphere-listener']
问题:
-
有没有办法去AFRAME.unregisterComponent()?
-
我是否只是错误地构建组件,因为它们具有状态依赖性?我开始认为他们应该是无国籍的 .
-
如果是这样,我如何将函数从react类传递到模式?像这样:
<a-sphere radius="30" sphere-listener={
cb:$ {()=> {console.log('call back')}}} />
谢谢,
约旦
1 回答
组件应在全局级别注册,而不是在运行时注册 . 您不应该像DOM元素一样注册和取消注册组件,因为没有太多好处 . 但如果你必须:
delete AFRAME.components['sphere-listener']
. EDIT :我确实看到你试图将React变量关闭到一个组件中 . 注册/取消注册有点工作,但我建议将它们分离 .如果需要将数据传递到组件中,可以使用
schema
,并通过模式绑定数据(例如,somecomponent={{foo: this.state.blah}}
) .你不能传递功能 . 您应该使用事件侦听器进行通信
<Entity events={{collide: () => {}}>
,并且可以在A-Frame级别发出事件 .重要的是要区分在A-Frame组件(3D,VR,事件)中应该执行哪些操作以及在React级别应该执行哪些操作(视图层,数据绑定) .