Sketch.View
Sketch.View 是 Sketch 的视图容器组件,用于包裹和布局子节点。
它是构建 Sketch 渲染树的重要容器,通常用于组织和排列子元素。
示例
React
tsx
import React, { useEffect } from 'react'
import { Sketch, StyleSheet } from '@sketchjs/react'
const styleSheet = StyleSheet.create({
root: {
width: 200,
height: 200,
backgroundColor: '#fff'
},
view: {
width: 100,
height: 100,
backgroundColor: '#000'
}
})
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'
import React from 'react'
const styleSheet = StyleSheet.create({
root: {
width: 200,
height: 200,
backgroundColor: '#fff'
},
view: {
width: 100,
height: 100,
backgroundColor: '#000'
}
})
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}
>
<Sketch.View style={styleSheet.view}/>
</Sketch.Root>
</>
)
}
})API 属性
React
| 属性 | 说明 | 类型 | 默认值 | 是否必填 |
|---|---|---|---|---|
| style | 样式 | StyleSheetDeclaration | - | false |
| children | 子元素 | SketchElementChild | - | false |
Vue
| 属性 | 说明 | 类型 | 默认值 | 是否必填 |
|---|---|---|---|---|
| style | 样式 | StyleSheetDeclaration | - | false |
使用说明 / 注意事项
Sketch.View可作为根节点或任意层级容器使用- 建议通过
StyleSheet.create()管理样式和布局 - 可嵌套多个
Sketch.View进行复杂布局