I have a component that is a container for a
<canvas>
class App extends React.Component {
ctx: CanvasRenderingContext2D;
canvas: HTMLCanvasElement;
componentDidMount() {
this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
this.forceUpdate();
}
render() {
const circle = this.ctx ? <Circle ctx={this.ctx} /> : '';
return (
<canvas ref={ref => (this.canvas = ref as HTMLCanvasElement)}>
{circle}
</canvas>
);
}
}
const Circle = ({ ctx }: { ctx: CanvasRenderingContext2D }) => {
ctx.arc(10, 10, 10, 0, 6);
ctx.stroke();
return null;
};
forceUpdate
ctx
componentWillMount
this.canvas
I think one way to do that would be as below:
class App extends React.Component {
ctx: CanvasRenderingContext2D;
canvas: HTMLCanvasElement;
constructor(props){
super(props);
this.state={ ctx:null }
}
componentDidMount() {
this.setState({ctx:this.canvas.getContext('2d') as CanvasRenderingContext2D})
}
render() {
const circle = this.state.ctx? <Circle ctx={this.state.ctx} /> : '';
return (
<canvas ref={ref => (this.canvas = ref as HTMLCanvasElement)}>
{circle}
</canvas>
);
}
}