gpt4 book ai didi

javascript - 在 React 组件上公开方法

转载 作者:行者123 更新时间:2023-12-01 02:04:50 25 4
gpt4 key购买 nike

这是我的代码

import React, { Component } from "react";
import { render } from "react-dom";

class CView extends Component {
someFunc() {
alert(1);
}

render() {
return <div>Hello, there</div>;
}
}

class App extends Component {
getControl() {
this.cv = <CView />;
return this.cv;
}

render() {
return (
<div>
<h2 onClick={() => this.cv.someFunc()}>Click Me</h2>
{this.getControl()}
</div>
);
}
}

render(<App />, document.getElementById("root"));

也可通过 https://codesandbox.io/s/k2174z4jno 获取

当我单击 h2 标签时,收到一条错误消息,指出 someFunc 未定义。如何公开组件的函数以便其他组件可以访问它?

谢谢

最佳答案

我认为this.cv = <CView />;不会直接返回CView组件的实例。

onClick={() => {
console.log(this.cv instanceof CView); // false
this.cv.someFunc();
}}

但是如果您尝试使用引用,您将访问它。

class App extends Component {
constructor(props) {
super(props)
this.cv = React.createRef();
}

onClick() {
this.cv.current.someFunc();
}

render() {
return (
<div>
<h2 onClick={() => this.onClick()}>Click Me</h2>
<CView ref={this.cv} />
</div>
);
}
}

不过,它更像是“ react 方式”。 https://codesandbox.io/s/vy61q9o8xy

关于javascript - 在 React 组件上公开方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197665/

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