在我的父组件中:
<div>
<h3>Option <span>{this.state.currentOption + 1}</span> of <span>{this.state.options}</span></h3>
<Button onClick={this.handleOption} variant="primary" type="submit">
{` Next >>`}
</Button>
</div>
Run Code Online (Sandbox Code Playgroud)
我正在调用一个钩子:
handleOption = event => {
event.preventDefault();
let option = this.state.currentOption;
const numOptions = this.state.stackOptions.length;
if (++option >= numOptions) {
option = 0;
}
this.setState({
currentOption: option,
});
}
Run Code Online (Sandbox Code Playgroud)
我希望循环遍历对象数组以在 Canvas 中渲染:
import React, { useRef, useEffect } from 'react'
const StackRender = props => {
const canvasRef = useRef(null)
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [])
return <canvas ref={canvasRef} {...props}/>
}
Run Code Online (Sandbox Code Playgroud)
但是,子组件(画布)不会随着父状态更改而更新。
添加props.name到useEffect依赖项数组中,以便每当更改时都会调用该函数props.name:
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [props.name])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5579 次 |
| 最近记录: |