Sketch.Root
Sketch.Root 是 Sketch 应用的根节点组件,用于:
- 初始化渲染环境
- 挂载 Sketch 实例
- 响应生命周期事件(初始化完成 / 元素更新)
通常与 <canvas> 配合使用,是整个渲染树的核心容器。
示例
React
tsx
import React, { useEffect } from 'react'
import { Sketch, StyleSheet } from '@sketchjs/react'
const styleSheet = StyleSheet.create({
root: {
width: 200,
height: 200,
backgroundColor: '#fff'
}
})
export const SketchView: React.FC = () => {
const sketch = Sketch.useSketch()
const canvasRef = React.useRef<HTMLCanvasElement>(null)
const handleSketchElementUpdate = () => console.log('sketch update')
const handleSketchInitialized = () => console.log('sketch initialized')
const initSketch = () => {
const canvas = canvasRef.current
const ctx = canvas?.getContext('2d')
if (!canvas || !ctx) return
return sketch.init({ canvas, ctx })
}
useEffect(() => {
initSketch()
}, [])
return (
<>
<canvas ref={canvasRef}/>
<Sketch.Root
autoRender
sketch={sketch}
style={styleSheet.root}
onUpdate={handleSketchElementUpdate}
onReady={handleSketchInitialized}
/>
</>
)
}Vue
tsx
import { defineComponent, onMounted, ref } from 'vue'
import { Sketch, StyleSheet } from '@sketchjs/vue'
const styleSheet = StyleSheet.create({
root: {
width: 200,
height: 200,
backgroundColor: '#fff'
}
})
export const SketchView = defineComponent({
name: 'SketchView',
setup () {
const sketch = Sketch.useSketch()
const canvasRef = ref<HTMLCanvasElement | null>(null)
const handleSketchElementUpdate = () => console.log('sketch update')
const handleSketchInitialized = () => console.log('sketch initialized')
const initCanvas = () => {
const canvas = canvasRef.value
const ctx = canvas?.getContext('2d')
if (!canvas || !ctx) return
return sketch.value.init({ canvas, ctx })
}
onMounted(() => initCanvas())
return () => (
<>
<canvas ref="canvasRef"/>
<Sketch.Root
autoRender
sketch={sketch.value}
style={styleSheet.root}
onReady={handleSketchInitialized}
onUpdate={handleSketchElementUpdate}
/>
</>
)
}
})API 属性
React
| 属性 | 说明 | 类型 | 默认值 | 是否必填 |
|---|---|---|---|---|
| sketch | sketch 实例 | SketchRoot | - | false |
| autoRender | 是否自动渲染 | boolean | - | false |
| onReady | 初始化完成事件回调 @param event | (event: Event<SketchRoot>) => void | - | false |
| onUpdate | 元素更新事件回调 @param event | (event: Event<SketchElement>) => void | - | false |
| style | 样式 | StyleSheetDeclaration | - | false |
| children | 子元素 | SketchElementChild | - | false |
Vue
| 属性 | 说明 | 类型 | 默认值 | 是否必填 |
|---|---|---|---|---|
| autoRender | 是否自动渲染 | boolean | - | false |
| sketch | sketch 实例 | SketchRoot | - | false |
| style | 样式 | StyleSheetDeclaration | - | false |
| ready | 初始化完成事件回调 | - | - | - |
| update | 元素更新事件回调 | - | - | - |
使用说明 / 注意事项
- 若
autoRender为false,需手动调用sketch.render() - 对于性能优化,可关闭
autoRender并手动触发渲染 - 样式使用
StyleSheet.create()统一管理