更新循环 matter.js (IIFE) 无法访问 class 组件的道具?

Update loop matter.js (IIFE) no access to class component's props?

我有这个“下拉菜单”,它使用 Matter.js 2d 物理引擎从顶部直接下拉:https://github.com/NeilSentence/galerie-sens

let world, engine, runner

const { Engine, Runner, World, Bodies, MouseConstraint, Composites, Body } = Matter

class Scene extends React.Component {
    
    constructor(props){
        super(props)
        this.state = {
            removeNonMenuBlocks: this.props.switchsections
        }
    }
    componentDidMount(){
        const runCode = () => {
            // set up all matter.js stuff here (works!).
            // At the bottom, an IIFE called update:
        
            (function update(removeNonMenuBlocks){
                requestAnimationFrame(update)
                // updates CSS positions of DOM elements. works(!)
                // but I need access to the class props here, to dynamically remove 
                // objects from world in real-time, as I do when HTML classes change
                // such as when "delayed-fallable" class is added 
                console.log(removeNonMenuBlocks) 
                // just prints an ever-increasing number
                Engine.update(engine)
            })(this.state.removeNonMenuBlocks)
        }
        run()
    }
}

我的直觉是,不断增加的数字是一件好事,因为这意味着某些东西确实在更新。但是如何达到多汁状态呢?

使用Scene组件的地方有“parent state”,通过prop(bool)传入

switchsections={()=>{return this.state.switchsections}}  

完整项目在 src/components/menudrop.js

状态

回答你的问题“但是如何到达多汁的状态?”:

您需要绑定 this-上下文,例如:

  constructor(props){
    // ...
    this.update = this.update.bind(this);
  }

  update(){
    // ...
    console.log( this.state.removeNonMenuBlocks ); // read the state
    this.setState({ removeNonMenuBlocks: true });  // set the state
    // ...
  }

道具

回答你的问题“(IIFE)无法访问class 组件的道具?”:

同样的故事:您可以在绑定到组件 this-context 的函数中访问组件属性(例如在上面的更新函数中)。

IIFE

但是,在您的示例代码中没有理由使用 IIFE:此处 IIFE(显然)旨在封装第一次调用时的状态,但您想要当前状态,而不是一个旧的。

事实上,它并没有按照那里的使用方式工作:update函数使用了参数removeNonMenuBlocksrequestAnimationFrame(update)没有给出。