javascript - 如何在打字稿类中调用反应组件内部定义的函数?
问题描述
export class abc extends React.Component<IProps, IState> {
function(name: string) {
console.log("I wish to call this function"+ name);
}
render() {
return (
<div>Hello</div>
);
}
}
现在我想将上面定义的组件的函数方法调用到另一个 xyz.ts 类(不是反应组件)中是否可以这样做?
解决方案
您可以像这样使用侦听器模式:
export interface IListener {
notify: (name:string) => void;
}
export class Listener {
listener : IListener[] = [];
addListener(listener: IListener) {
this.listener.add(listener)
}
notifyListener() {
this.listener.forEach((listener) => {
listener.notify("abc");
});
}
}
export class abc extends React.Component<IProps, IState> implements IListener {
componentDidMount() {
// register this class as a listener
new Listener().addListener(this);
}
public notify(name:string) {
this.test(name);
}
test(name: string) {
console.log("I wish to call this function"+ name);
}
render() {
return (
<div>Hello</div>);
}
}
推荐阅读
- javascript - 使用 Debounced Scroll 事件固定元素以提高性能
- postgresql - 是否可以通过添加更多索引来加速此查询?
- php - PHP:如何只替换=而不替换<=和>=
- delphi - 构造函数在初始化类变量时抛出 eaccessviolation
- git - 什么是 git status 替代品!svn状态结果
- json - 如何根据上述jq数组中对象中的元素值选择/获取对象元素的(对象数组)键?
- nginx - 向上游发送请求时,nginx 失败(32:管道损坏),
- python - 使用子列表进行列表理解
- opencv - 找到我们从远处在图像上看到的颜色
- python - 在 python 中切片的这种行为是什么?