我沒有試圖做任何hacky使用refs。我只需要元素的ref,因爲元素是一個畫布,並且在畫布上繪製需要它的參考。React - 獲取父組件中存在的ref參數
class Parent extends Component {
clickDraw =() => {
// when button clicked, get the canvas context and draw on it.
// how?
}
render() {
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child />
</div>
);
}
}
class Child extends Component {
componentDidMount() {
const ctx = this.canvas.getContext('2d');
// draw something on the canvas once it's mounted
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
render() {
return (
<canvas width={300}
height={500}
ref={canvasRef => this.canvas = canvasRef}>
</canvas>
);
}
}
=====
東西我想(這在技術上的作品,但覺得很奇怪),是在父定義<canvas>
,所以在它的引用功能,this
指父組件。然後我把<canvas>
和this.canvas
作爲兩個獨立的道具傳遞給孩子。我將<canvas>
(名爲this.props.canvasJSX
)返回到子項的渲染函數中,並且我使用this.canvas
(名爲this.props.canvasRef
)獲取其上下文來繪製它。見下:
class Parent extends Component {
clickDraw =() => {
// now I have access to the canvas context and can draw
const ctx = this.canvas.getContext('2d');
ctx.fillStyle = "#00FF00";
ctx.fillRect(0,0,275,250);
}
render() {
const canvas = (
<canvas width={300}
height={500}
ref={canvasRef => this.canvas = canvasRef}>
</canvas>
);
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child canvasJSX={canvas}
canvasRef={this.canvas} />
</div>
);
}
}
class Child extends Component {
componentDidMount() {
const ctx = this.props.canvasRef.getContext('2d');
// draw something on the canvas once it's mounted
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
render() {
return this.props.canvas;
}
}
有沒有更實際的標準方法?
可能的重複[如何訪問父組件中的子組件的引用>](https://stackoverflow.com/questions/37647061/how-do-i-access-refs-of-a-child -component-in-the-parent-component) – arpl
請在父組件中使用getter和setter – zloctb