Javascript 如何用更新方法和mithril组件封装状态
我想渲染每个请求动画帧都会更新的状态 我想用更新方法和相应的组件封装状态: 但这失败了,因为它没有正确使用mithril组件Javascript 如何用更新方法和mithril组件封装状态,javascript,mithril.js,Javascript,Mithril.js,我想渲染每个请求动画帧都会更新的状态 我想用更新方法和相应的组件封装状态: 但这失败了,因为它没有正确使用mithril组件 import * as Vnode from 'mithril/render/vnode'; import * as h from 'mithril/hyperscript'; export default function Play() { // background is another encapsulation like Play let backg
import * as Vnode from 'mithril/render/vnode';
import * as h from 'mithril/hyperscript';
export default function Play() {
// background is another encapsulation like Play
let background = new Background(this);
let data;
this.init = d => {
data = d;
background.init();
};
this.update = delta => {
background.update(delta);
};
this.component = ({
view() {
return h('div.' + data,
[Vnode(background.component)]
);
});
}
渲染代码:
import mrender from 'mithril/render';
import * as Vnode from 'mithril/render/vnode';
export default function MRender(mountPoint) {
this.render = (component) => {
mrender(mountPoint, Vnode(component));
};
}
用法:
let mrender = new MRender(element);
let play = new Play();
function step() {
play.update();
mrender.render(Vnode(play.component));
requestAnimationFrame(step);
};
step();
我希望状态突变和渲染代码位于同一位置,因为状态与视图动画有关。如果我理解正确,您希望能够在requestAnimationFrame更新组件时管理组件的内部状态吗?以下内容可能会让您走上正确的道路:
const m = require('mithril');
//Use a closure to manage internal state of component
const play = initialVnode => {
const {
timestamp
} = initialVnode.attrs;
const start = timestamp;
return {
view: vnode => m('ul',[
m('li',`Start: ${start}`),
m('li',`Current timestamp: ${vnode.attrs.timestamp}`),
])
}
};
let reqID;
const step = timestamp => {
if( timestamp ){ //Start animating when timestamp is defined
m.render(document.body, m(play,{
timestamp,
}));
}
reqID = requestAnimationFrame(step);
if( reqID === 60 ){ //Add condition to stop animating
cancelAnimationFrame(reqID);
}
};
step();
我希望这有帮助