如何将函数作为参数传递给TypeScript中的ReactJS组件

Lam*_*ert 13 typescript reactjs

我正在尝试创建一个可重用的ReactJS按钮组件,并需要有关如何将函数传递给组件然后将其用作单击事件的帮助.按钮上的单击事件不起作用.

以下是调用组件的代码:

export var MyPublicFunction = function (inArg: number) {
    alert(inArg);
}

ReactDOM.render(<MyButton name="My Button" clickFunction={MyPublicFunction(1)} >Button</MyButton>, document.getElementById('content'));
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试编写的组件:

interface myProps {
   name: string;
   clickFunction: any
}

class MyButton extends React.Component<myProps, {}> {

    constructor(props: myProps) {
        super(props);
    }

    render() {
        return (<div>
            <button ref="btn1"  onClick={this.props.clickFunction} >
                {this.props.name}
             </button>
        </div>);
    } //end render.
} //end class.
Run Code Online (Sandbox Code Playgroud)

Rya*_*ugh 10

<MyButton name="My Button" clickFunction={MyPublicFunction(1)} >
Run Code Online (Sandbox Code Playgroud)

表达MyPublicFunction(1)在含有表达的评估期间立即被调用.你需要的是提供一个功能clickFunction:

<MyButton name="My Button" clickFunction={() => MyPublicFunction(1)} >
Run Code Online (Sandbox Code Playgroud)

请注意,如果您编写了类似的内容,则会出现类型错误:

interface myProps {
   name: string;
   clickFunction: () => void;
}
Run Code Online (Sandbox Code Playgroud)