test: class component testing

This commit is contained in:
dntzhang 2019-10-05 08:46:44 +08:00
parent e2f3b7534f
commit b746bb11e4
3 changed files with 38 additions and 18 deletions

View File

@ -27,6 +27,7 @@
</noscript>
<div id="root"></div>
<div id="root2"></div>
<div id="root3"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

View File

@ -24,4 +24,26 @@ Preact.render(<Comp />, document.querySelector('#root'))
Preact.render(<Comp />, document.querySelector('#root2'))
class CompB extends Preact.Component {
static css = `
h1{
color: green;
}
`
render() {
return <>
<h1>
I'm green
</h1>
<div>
I'm black
</div>
</>
}
}
//Test class Component
Preact.render(<CompB />, document.querySelector('#root3'))

View File

@ -1,34 +1,31 @@
import { options } from 'preact'
import { getStyleId, appendStyle } from './style'
let componentNode;
let componentNode
// store a reference to the "current component" vnode
let oldDiff = options._diff || options.__b;
let oldDiff = options._diff || options.__b
options._diff = options.__b = vnode => {
componentNode = vnode;
if (oldDiff) oldDiff(vnode);
};
componentNode = vnode
if (oldDiff) oldDiff(vnode)
}
// reset component reference at end of diffing:
let oldDiffed = options.diffed;
let oldDiffed = options.diffed
options.diffed = vnode => {
if (componentNode === vnode) componentNode = null;
if (oldDiffed) oldDiffed(vnode);
};
if (componentNode === vnode) componentNode = null
if (oldDiffed) oldDiffed(vnode)
}
// our vnode hook looks up the associated component
let old = options.vnode;
let old = options.vnode
options.vnode = vnode => {
const component = componentNode && (componentNode._component || componentNode.__c);
const component = componentNode && (componentNode._component || componentNode.__c)
if (component) {
// component is the component instance
//component.css;
const styleId = getStyleId(component.constructor);
const styleId = getStyleId(component.constructor)
appendStyle(component.constructor.css, styleId);
// example: assign component's unique CSS ID:
(vnode.props || (vnode.props = {}))[styleId] = ''
}
if (old) old(vnode);
};
if (old) old(vnode)
}