React 中使用 ref 获取子组件事件的技巧
在 React 中,可以通过使用 ref 来获取子组件的事件。以下是一个示例:
首先,在父组件中创建一个 ref 对象:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
handleClick() {
// 通过 ref 获取子组件的事件
this.childRef.current.handleEvent();
}
render() {
return (
<div>
<ChildComponent ref={this.childRef} />
<button onClick={() => this.handleClick()}>触发子组件事件</button>
</div>
);
}
}
然后,在子组件中,将需要获取的事件绑定到 ref 对象上:
class ChildComponent extends React.Component {
handleEvent() {
console.log('子组件的事件被触发');
}
render() {
return (
<div>
子组件
</div>
);
}
}
在上面的例子中,通过在父组件中创建一个 ref 对象'childRef',并将其传递给子组件的'ref'属性。然后,在父组件的'handleClick'方法中,通过'this.childRef.current'来获取子组件实例,并调用子组件的'handleEvent'方法。
当点击父组件中的按钮时,将会触发子组件的事件,并在控制台中输出'子组件的事件被触发'。
原文地址: https://www.cveoy.top/t/topic/Rz4 著作权归作者所有。请勿转载和采集!