获取父组件中的子组件中的ref
我没有试图做任何hacky使用refs。 我只需要元素的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
作为两个独立的道具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;
}
}
有没有更实际的标准方法?
实际上,您应该使用第一种方法,并且可以访问父级中的子元素参考
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
。
如果无法避免,从React文档中提取的建议模式将是:
import React, {Component} from 'react';
const Child = ({setRef}) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Call function on Child dom element
this.childInput.focus();
}
setRef(input) {
this.childInput = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
父母通过一个函数作为与父母的this
绑定。 React将调用Child的ref
回调setRef
,并将childInput
属性附加到this
,正如我们已经注意到的那样指向了Parent 。
上一篇: Get the ref present in child component in the parent component