gpt4 book ai didi

javascript - React - 获取父组件中子组件中的引用

转载 作者:可可西里 更新时间:2023-11-01 02:40:53 25 4
gpt4 key购买 nike

我不会尝试使用 refs 做任何骇人听闻的事情。我只需要元素的引用,因为元素是 Canvas ,要在 Canvas 上绘图,你需要它的引用。

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作为两个独立的 Prop 给 child 。我返回 <canvas> (名为 this.props.canvasJSX )在 child 的渲染函数中,我使用 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;
}
}

是否有更标准的方法来实现这一目标?

最佳答案

你实际上应该使用第一种方法,你可以访问父元素中的子元素 refs

class Parent extends Component {
clickDraw = () => {
// when button clicked, get the canvas context and draw on it.
const ctx = this.childCanvas.canvas.getContext('2d');
ctx.fillStyle = "#00FF00";
ctx.fillRect(0,0,275,250);
}

render() {
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child ref={(ip) => this.childCanvas = ip}/>;
</div>
);
}
}


class Child extends Component {
constructor() {
super();
this.canvas = null;
}
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>
);
}
}

您只能在子组件声明为 class 时使用此方法。

关于javascript - React - 获取父组件中子组件中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com