addComponent动态添加脚本组件的问题

我在脚本中new cc.Node(‘Sprite’)创建了一个节点,想给这个节点添加一个脚本组件,并且把我自己写的一个bg_select.ts脚本绑到节点上,请问应该怎么写呀?

let node=new cc.Node()
node.addComponent(bg_select)

直接引用么?需不需要在脚本中先import {bg_select} from “./bg_select.ts”;
或者有没有特殊的目录结构的要求?
类似resource.load必须要在resources目录一样?

按照您说的方法试了一下,还是报错:
Uncaught TypeError TypeError: Cannot read properties of undefined (reading ‘getComponent’)
完整代码如下:
const {ccclass, property} = cc._decorator;

import PokeNode from “./PokeNode”;

@ccclass

export default class FrameTest extends cc.Component {

@property(cc.Label)

label: cc.Label = null;

@property

text: string = 'hello';

// @property

// defaultFrame:{

//     default: null,

//     type: cc.SpriteFrame

// }

// LIFE-CYCLE CALLBACKS:

onLoad () {

    //添加子节点,子节点添加背景图片,默认active为false

    let pokeNode = new cc.Node('sprite');

    //2.添加背景图片

    var sp = pokeNode.addComponent(cc.Sprite);

    cc.resources.load(

        "Texture/001.tex_5",cc.SpriteFrame,(err,spriteFrame) => {

            pokeNode.getComponent(cc.Sprite).spriteFrame  = spriteFrame ;

        });

        pokeNode.active = true ;

        pokeNode.parent = this.node;

   

    //1.添加子节点

    let selectNode = new cc.Node('sprite');

    //2.添加背景图片

    var sp = selectNode.addComponent(cc.Sprite);

    cc.resources.load(

        "Texture/button_goal_task01_003-hd",cc.SpriteFrame,(err,spriteFrame) => {

            selectNode.getComponent(cc.Sprite).spriteFrame  = spriteFrame ;

        });

    selectNode.active = true ;

   

    //将子节点添加到节点内

    selectNode.parent = pokeNode;

    //添加脚本组件

    pokeNode.addComponent(PokeNode);

    pokeNode.on(cc.Node.EventType.TOUCH_START, function(eventTouch){

        selectNode.active ? selectNode.active = false : selectNode.active = true ;

        //获取触点位置

        var touchPos = eventTouch.getLocation();

        //调用PokeNode.convertTouchPosToCell()

        var cellPos = this.node.getComponent(PokeNode).convertTouchPosToCell(touchPos);

        cc.log("mouse down" + selectNode.active);

    });

   

}

start () {

}

// update (dt) {}

}

解决了,一是需要import,二是this.node.getComponent(“PokeNode”)必须加双引号

另外,如果在on事件监听中用this.node,必须加第三个参数this或bind(this);否则this.node为undefined
示例如下:
on(event,function(event){
this.node.getComponent(“PokeNode”).function();
},this)