在线体验地址:han-hooks.netlify.com/ css
![]()
在本文中,我将使用React Hooks建立一个html canvas 画图网站,我将使用create-react-app脚手架从零开始构建项目。最后这个应用程序有诸如清除、撤销和使用localStorage基本功能。html
本文我将向您展现任何构建自定义Hooks和在普通的Hooks中重用有状态逻辑。react
咱们首先使用create-react-app建立一个新的React应用程序。canvas
$ npx create-react-app canvas-and-hooks
$ cd canvas-and-hooks/
$ yarn start
复制代码
您的浏览器会打开http://localhost:3000/
,而后您会看到一个旋转的React logo图片,那么,您如今能够开始了...数组
用您喜欢的编辑器打开src/App.js
文件📃,而后替换成如下内容:浏览器
import React from 'react'
function App() {
return (
<canvas
width={window.innerWidth}
height={window.innerHeight}
onClick={e => {
alert(e.clientX)
}}
/>
)
}
export default App
复制代码
在浏览器窗口中点击任意一处,若是会弹出一个弹出框:显示您鼠标🖱️点击的x坐标,很好!应用程序跑起来了。bash
如今,咱们真正的画一些东西。这样的话咱们就须要canvas 元素的ref,因此,开始使用今天的第一个hook useRef吧:app
import React from 'react'
function App() {
const canvasRef = React.useRef(null)
return (
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={e => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
// implement draw on ctx here
}}
/>
)
}
export default App
复制代码
一般,在React中你不须要一个ref来作更新的操做。可是canvas不像其它的DOM元素。大多数DOM元素都有一个属性,好比说:value,你能够直接更新它。在canvas中容许✅您使用context(本🌰:ctx)来画一些东西。为此,咱们不得不使用ref,它是对实际canvas DOM元素的引用。编辑器
如今咱们有了canvas上下文,是时候画一些东西了。为此,粘贴复制如下代码绘制一个SVG hook。它与hooks无关,若是您不理解它也不须要担忧😓。函数
import React from 'react'
const HOOK_SVG = 'm129.03125 63.3125c0-34.914062-28.941406-63.3125-64.519531-63.3125-35.574219 0-64.511719 28.398438-64.511719 63.3125 0 29.488281 20.671875 54.246094 48.511719 61.261719v162.898437c0 53.222656 44.222656 96.527344 98.585937 96.527344h10.316406c54.363282 0 98.585938-43.304688 98.585938-96.527344v-95.640625c0-7.070312-4.640625-13.304687-11.414062-15.328125-6.769532-2.015625-14.082032.625-17.960938 6.535156l-42.328125 64.425782c-4.847656 7.390625-2.800781 17.3125 4.582031 22.167968 7.386719 4.832032 17.304688 2.792969 22.160156-4.585937l12.960938-19.71875v42.144531c0 35.582032-29.863281 64.527344-66.585938 64.527344h-10.316406c-36.714844 0-66.585937-28.945312-66.585937-64.527344v-162.898437c27.847656-7.015625 48.519531-31.773438 48.519531-61.261719zm-97.03125 0c0-17.265625 14.585938-31.3125 32.511719-31.3125 17.929687 0 32.511719 14.046875 32.511719 31.3125 0 17.261719-14.582032 31.3125-32.511719 31.3125-17.925781 0-32.511719-14.050781-32.511719-31.3125zm0 0'
const HOOK_PATH = new Path2D(HOOK_SVG)
const SCALE = 0.3
const OFFSET = 80
function draw(ctx, location) {
ctx.fillStyle = 'deepskyblue'
ctx.shadowColor = 'dodgerblue'
ctx.shadowBlur = 20 ctx.save()
ctx.scale(SCALE, SCALE) ctx.translate(location.x / SCALE - OFFSET, location.y / SCALE - OFFSET)
ctx.fill(HOOK_PATH)
ctx.restore()
}
function App() {
const canvasRef = React.useRef(null)
return (
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={e => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
draw(ctx, { x: e.clientX, y: e.clientY })
}}
/>
)
}
export default App
复制代码
上面的代码是为了在坐标(x,y)绘制一个SVG形状(一个鱼钩)。
试一试,看看它是否起做用。
咱们要添加的下一个功能是Clean和Undo按钮🔘。为此,咱们将使用useState hook来跟踪用户交互。
import React from 'react'
// ...
// canvas draw function
// ...
function App() {
const [locations, setLocations] = React.useState([])
const canvasRef = React.useRef(null)
return (
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={e => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
draw(ctx, newLocation)
}}
/>
)
}
export default App
复制代码
因此,咱们为app添加了state。您能够在return语句上面添加console.log(locations)
来验证一下。随着用户点击,您会看到打印的数组。
目前,咱们对state没有任何操做。咱们仍是像之前同样绘制了hooks。咱们来看看用useEffect hook如何修复这个问题。
import React from 'react'
// ...
// canvas draw function
// ...
function App() {
const [locations, setLocations] = React.useState([])
const canvasRef = React.useRef(null)
React.useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, window.innerHeight, window.innerWidth)
locations.forEach(location => draw(ctx, location))
})
return (
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={e => {
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
}}
/>
)
}
export default App
复制代码
这里作了不少事情咱们来一一拆解一下。咱们把onClick事件处理函数的绘制函数移动到useEffect回掉里。这很重要,由于在画布上绘制由app的状态决定,这是个反作用。后面咱们会使用localStorage来保持持久化,在state更新的时候这也会是个反作用。
我也对canvas自己的实际绘制作了一些更改,在当前实现中,每次render渲染先清除canvas而后再绘制全部位置,咱们能够作的比这聪明一点。但为了保持简单,就留给读者去优化吧。
咱们已经完成了全部最难的部分,如今添加新功能应该很简单了。咱们来建立清除按钮吧。
import React from 'react'
// ...
// canvas draw function
// ...
function App() {
const [locations, setLocations] = React.useState([])
const canvasRef = React.useRef(null)
React.useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, window.innerHeight, window.innerWidth)
locations.forEach(location => draw(ctx, location))
})
function handleCanvasClick(e) {
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
}
function handleClear() {
setLocations([])
}
return (
<>
<button onClick={handleClear}>Clear</button>
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={handleCanvasClick}
/>
</>
)
}
export default App
复制代码
清除功能只是一个简单的state更新:咱们经过设置它为一个空数组来清除state,这很简单,对吗?
进一步,我也把canvas onClick事件处理移动到一个单独的函数里。
咱们来添加另一个功能:撤销。一样的原则,即便这种状态更新有点棘手。
import React from 'react'
// ...
// canvas draw function
// ...
function App() {
const [locations, setLocations] = React.useState([])
const canvasRef = React.useRef(null)
React.useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, window.innerHeight, window.innerWidth)
locations.forEach(location => draw(ctx, location))
})
function handleCanvasClick(e) {
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
}
function handleClear() {
setLocations([])
}
function handleUndo() {
setLocations(locations.slice(0, -1))
}
return (
<>
<button onClick={handleClear}>Clear</button>
<button onClick={handleUndo}>Undo</button>
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={handleCanvasClick}
/>
</>
)
}
export default App
复制代码
由于React中任何state更新都必须是不可变的,因此咱们不能使用像locations.pop()
来清除数组中最近的一项。咱们的操做不能改变原始的locations数组。方法是使用slice,复制全部项直到最后一个。你可使用locations.slice(0, locations.length - 1)
,可是slice有个更聪明的操做数组最后一位的-1。
在咱们开始以前,咱们整理一下html,而后添加一个css样式文件。在buttons按钮外面添加以下的div。
import React from 'react'
import './App.css'
// ...
// canvas draw function
// ...
function App() {
// ...
return (
<>
<div className="controls">
<button onClick={handleClear}>Clear</button>
<button onClick={handleUndo}>Undo</button>
</div>
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={handleCanvasClick}
/>
</>
)
}
export default App
复制代码
css样式以下:
*,
*:before,
*:after {
box-sizing: border-box;
}
body {
background-color: black;
}
.controls {
position: absolute;
top: 0;
left: 0;
}
button {
height: 3em;
width: 6em;
margin: 1em;
font-weight: bold;
font-size: 0.5em;
text-transform: uppercase;
cursor: pointer;
color: white;
border: 1px solid white;
background-color: black;
}
button:hover {
color: black;
background-color: #00baff;
}
button:focus {
border: 1px solid #00baff;
}
button:active {
background-color: #1f1f1f;
color: white;
}
复制代码
看起来不错,咱们来看看下一个功能:持久化。
咱们以前提过,咱们也想要咱们的绘制保存在localStroage中,这也是另一个反作用,咱们将添加另一个useEffect。
import React from 'react'
import './App.css'
// ...draw function
function App() {
const [locations, setLocations] = React.useState(
JSON.parse(localStorage.getItem('draw-app')) || [] )
const canvasRef = React.useRef(null)
React.useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, window.innerHeight, window.innerWidth)
locations.forEach(location => draw(ctx, location))
})
React.useEffect(() => {
localStorage.setItem('draw-app', JSON.stringify(locations))
})
function handleCanvasClick(e) {
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
}
function handleClear() {
setLocations([])
}
function handleUndo() {
setLocations(locations.slice(0, -1))
}
return (
<>
<div className="controls">
<button onClick={handleClear}>Clear</button>
<button onClick={handleUndo}>Undo</button>
</div>
<canvas
ref={canvasRef}
width={window.innerWidth}
height={window.innerHeight}
onClick={handleCanvasClick}
/>
</>
)
}
export default App
复制代码
如今咱们已经完成了咱们要构建的全部功能,但还不够。关于books最酷的一件事是您可使用现有的hooks来组建新的自定义hooks。我建立一个自定义的usePersistentState hook来展现这一点。
import React from 'react'
import './App.css'
// ...draw function
// our first custom hook!
function usePersistentState(init) {
const [value, setValue] = React.useState(
JSON.parse(localStorage.getItem('draw-app')) || init
)
React.useEffect(() => {
localStorage.setItem('draw-app', JSON.stringify(value))
})
return [value, setValue]}
function App() {
const [locations, setLocations] = usePersistentState([])
const canvasRef = React.useRef(null)
React.useEffect(() => {
const canvas = canvasRef.current
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, window.innerHeight, window.innerWidth)
locations.forEach(location => draw(ctx, location))
})
function handleCanvasClick(e) {
const newLocation = { x: e.clientX, y: e.clientY }
setLocations([...locations, newLocation])
}
function handleClear() {
setLocations([])
}
function handleUndo() {
setLocations(locations.slice(0, -1))
}
return (
// ...
)
}
export default App
复制代码
这里,咱们建立了第一个自定义hook而且从App组件中提取了与从localStorage保存和获取状态相关的全部逻辑。咱们这样作的方式是usePersistentState hook能够被其它组件重用。这里没有任何特定于此组件的内容。
咱们重复这个技巧来操做canvas相关的逻辑。
import React from 'react'
import './App.css'
// ...draw function
// our first custom hook
function usePersistentState(init) {
const [value, setValue] = React.useState(
JSON.parse(localStorage.getItem('draw-app')) || init
)
React.useEffect(() => {
localStorage.setItem('draw-app', JSON.stringify(value))
})
return [value, setValue]
}
// our second custom hook: a composition of the first custom hook // and React's useEffect + useRef function usePersistentCanvas() { const [locations, setLocations] = usePersistentState([]) const canvasRef = React.useRef(null) React.useEffect(() => { const canvas = canvasRef.current const ctx = canvas.getContext('2d') ctx.clearRect(0, 0, window.innerWidth, window.innerHeight) locations.forEach(location => draw(ctx, location)) }) return [locations, setLocations, canvasRef] } function App() { const [locations, setLocations, canvasRef] = usePersistentCanvas() function handleCanvasClick(e) { const newLocation = { x: e.clientX, y: e.clientY } setLocations([...locations, newLocation]) } function handleClear() { setLocations([]) } function handleUndo() { setLocations(locations.slice(0, -1)) } return ( <> <div className="controls"> <button onClick={handleClear}>Clear</button> <button onClick={handleUndo}>Undo</button> </div> <canvas ref={canvasRef} width={window.innerWidth} height={window.innerHeight} onClick={handleCanvasClick} /> </> ) } export default App 复制代码
正如您所看到的,咱们的App组件变得很是小。 在localStorage中存储状态和在canvas上绘图相关的全部逻辑都被提取到自定义hooks。 您能够经过将hooks移动到hooks文件中来进一步清理此文件。 这样,其余组件能够重用这种逻辑,例如构成更好的hooks。
若是将hooks与生命周期方法(如componentDidMount,componentDidUpdate)进行比较,是什么让hooks如此特别? 看看上面的例子:
如今判断hooks是否真的要解决全部这些问题还为时尚早 - 以及可能会出现什么新的不良作法 - 但看看上面我对React的将来感到很是兴奋和乐观!