私はrefを使用して何かをしようとしていません。要素がキャンバスなので、要素への参照が必要です。キャンバス上に描画するためには、その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>
を定義するので、そのREFの関数で、this
親成分を意味します。次に、<canvas>
とthis.canvas
を2つの別々の小道具として子供に渡します。子のレンダリング機能に<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)親コンポーネントのコンポーネント) – arpl
getterとsetterを親コンポーネントで使用してください。コンポーネント – zloctb