我希望以下代码能够导致React
<canvas>
包含单词&#39; foo&#39; <canvas>
。并使用&#39; bar&#39; <span>
<span>
更新,但不是<canvas>
import React from 'react'
var CanvasTest = React.createClass({
componentDidMount() {
this.animate(this.props.text)
},
animate(str) {
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
ctx.clearRect(0,0,10,50)
ctx.fillText(str, 10, 50)
},
render() {
return (
<div>
<span>{this.props.text}</span>
<canvas id="canvas" width="100" height="100"></canvas>
</div>
)
}
})
export default React.createClass({
getInitialState() {
return {
str: 'foo'
}
},
componentDidMount() {
setTimeout(() => {
this.setState({ str: 'bar' })
}, 1000)
},
render() {
return (
<CanvasTest text={this.state.str}/>
)
}
})
答案 0 :(得分:0)
你可以使用&#34; componentWillReceiveProps&#34;在CanvasTest内部
componentWillReceiveProps(newProps) {
ctx.fillText(newProps.text, 10, 50);
// to re-render
this.forceUpdate();
}
答案 1 :(得分:0)
结果clearRect
只清除了canvas
的一小部分,请参阅下面的参数:
animate(str) {
var c = document.getElementById('canvas')
var ctx = c.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillText(str, 10, 50)
},