代码之家  ›  专栏  ›  技术社区  ›  Prasaad Patil

从reactjs typescript中的子组件调用时未调用父函数

  •  0
  • Prasaad Patil  · 技术社区  · 6 年前

    我正在用visual studio中的typescript在react中开发一个小型web应用程序。我有一个父组件和一个子组件,我想从子组件调用父组件的函数。我写了下面的代码,但似乎我做错了什么

    帕斯滕

    export class Parent extends React.Component<RouteComponentProps<{}>, {}>{
    constructor() {
        super()
        this.deleteFunction = this.deleteFunction.bind(this);
    }
    
    deleteFunction(){
    console.log('delete called from parent');
    }
    
    public render() {
        return (
                <div>
                     <Child deleteFunction={this.deleteFunction.bind(this)} />
                </div>
       )
    }
    

    童子军

    class ChildProps{
    deleteFunction: any;
    }
    
    
    export class Child extends React.Component<ChildProps, {}> {
    
    constructor() {
        super();
        this.handledeletebutton = this.handledeletebutton.bind(this);
    }
    
    handledeletebutton(){
       e.preventDefault();
       console.log('delete called from child');
       this.props.deleteFunction;
    }
    
    render(
        <div>
            < a href='#' onClick={this.handledeletebutton}>Delete</a>
       </div>
    )
    }
    

    我可以在控制台中看到孩子的日志,但看不到家长的日志。它似乎在处理.jsx文件,但我不知道为什么它不在typescript中。而且我在控制台中看不到任何错误。我对打字很陌生,所以也许我犯了个愚蠢的错误。有人能帮我吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Prasaad Patil    6 年前

    很简单。我只需要使用正确的语法。由于deleteFunction是一个函数,所以我必须在子组件中使用deleteFunction()。所以handleDeleteButton()如下

    handledeletebutton(){
        e.preventDefault();
        console.log('delete called from child');
        this.props.deleteFunction();<= Use as a function
     }