P粉5010077682023-09-03 00:25:16
useStateRef
似乎是一种反模式。您决定新状态是什么,所以如果您需要另一个对它的引用,您总是可以自己创建一个。我建议尽量减少画布上的属性,以防止不必要的重新渲染。
function App({ width, height }) { const canvas = React.useRef() const [color, setColor] = React.useState("white") // when color changes.. React.useEffect(() => { if (canvas.current) { const context = canvas.current.getContext('2d'); context.fillStyle = color context.fillRect(0, 0, width, height) } }, [color, width, height]) return <div> <canvas ref={canvas} width={width} height={height} /> <button onClick={_ => setColor("blue")} children="blue" /> <button onClick={_ => setColor("green")} children="green" /> <button onClick={_ => setColor("red")} children="red" /> </div> } ReactDOM.createRoot(document.querySelector("#app")).render(<App width={200} height={150} />)
canvas { display: block; border: 1px solid black; }
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="app"></div>
或者也许没有理由将颜色存储为状态。您可以自己创建setColor
函数并将其附加为事件监听器 -
function App({ width, height }) { const canvas = React.useRef() const setColor = color => event => { if (canvas.current) { const context = canvas.current.getContext('2d'); context.fillStyle = color context.fillRect(0, 0, width, height) } } return <div> <canvas ref={canvas} width={width} height={height} /> <button onClick={setColor("blue")} children="blue" /> <button onClick={setColor("green")} children="green" /> <button onClick={setColor("red")} children="red" /> </div> } ReactDOM.createRoot(document.querySelector("#app")).render(<App width={200} height={150} />)
canvas { display: block; border: 1px solid black; }
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="app"></div>
我还建议您查看SVG。我发现SVG的API与React模式更加契合,比Canvas API更好。每个的功能不同,但如果SVG适用于您的需求,那么值得考虑。