我有一个呈现<Particle />组件和<Particle />组件呈现函数的根组件:
render: function(){
var data = this.props.data,
canvas = document.createElement('canvas'),
context;
canvas.style.position = 'absolute';
canvas.style.top = data.y + 'px';
canvas.style.left = data.x + 'px';
context = canvas.getContext('2d');
context.drawImage(data.img, data.x, data.y, data.tileSize, data.tileSize, 0, 0, data.tileSize, data.tileSize);
return canvas;
}这将返回以下错误:
Uncaught Error: Invariant Violation: Particle.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.我看了一下Flipboard的react-canvas,但是找不到与我的情况类似的好例子。
所以任何帮助都是非常感谢的。
发布于 2015-08-11 11:44:01
您应该只返回一个带有引用的画布元素。此元素与DOM节点不同;React使用JSX将其转换为React组件:
render: function() {
return <canvas ref="canvas" />
}然后在生命周期方法中修改它:
componentWillReceiveProps: function() {
var canvas = React.findDOMNode(this.refs.canvas);
canvas.style.position = 'absolute';
// etc ...
}还可以在呈现中设置一些内联样式属性:
render: function() {
var styles = {
position: 'absolute',
top: this.props.data.y,
left: this.props.data.x
}
return <canvas ref="canvas" style={styles} />
}...but上下文/图形最好放在生命周期方法中,因为您需要访问dom节点。
https://stackoverflow.com/questions/31939251
复制相似问题