我正在尝试使用画布和脚本绘制一条对角线的矩形。但是,不幸的是,矩形单独显示在我的浏览器中。看起来脚本没有被执行。
代码:
import React, { Component } from 'react';
import '../App.css';
class Graphics extends Component{
render(){
return(
<div id="canvas">
Draw a diagonal Line in Rectangular
<canvas id="myCanvas" className="canvas-style" width="200" height="100">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</div>
);
}
}
export default Graphics;
答案 0 :(得分:2)
您应该在componentDidMount()
内编写脚本标记。
答案 1 :(得分:0)
您可以使用以下代码
import React, { Component } from 'react';
import '../App.css';
class Graphics extends Component{
componentDidMount(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
}
render(){
return(
<div id="canvas">
Draw a diagonal Line in Rectangular
<canvas id="myCanvas" className="canvas-style" width="200" height="100">
</canvas>
</div>
);
}
}
export default Graphics;
答案 2 :(得分:0)
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
componentDidMount () {
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
}
render () {
return (
<div className="App">
<div id="canvas">
Draw a diagonal Line in Rectangular
<canvas
id="myCanvas"
className="canvas-style"
width="200"
height="100" />
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);