में बाल घटक में रेफरी प्रस्तुत करें मैं रेफरी का उपयोग करके कुछ भी हैकी करने की कोशिश नहीं कर रहा हूं। मुझे केवल तत्व को रेफरी चाहिए क्योंकि तत्व कैनवास है, और कैनवास पर आकर्षित करने के लिए आपको इसकी रेफरी चाहिए।प्रतिक्रिया - मूल घटक
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 -कंपोनेंट-इन-द-पैरेंट-घटक) – arpl
कृपया माता-पिता घटक – zloctb