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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35369013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:17:07  来源:igfitidea点击:

How to pass a function as an argument to a ReactJS component in TypeScript

reactjstypescript

提问by Lambert

I am trying to make a reusable ReactJS button component and need help on how to pass a function to a component and then use it as a click event. The click event on the button is not working.

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

Here is the code that will call the component:

下面是调用组件的代码:

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

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

Here it the component I'm trying to write:

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

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.

采纳答案by Ryan Cavanaugh

<MyButton name="My Button" clickFunction={MyPublicFunction(1)} >

The expression MyPublicFunction(1)is immediately invoked during evaluating of the containing expression. What you want is to provide a functionto clickFunction:

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

<MyButton name="My Button" clickFunction={() => MyPublicFunction(1)} >

Note that you would get a type error if you had written something like this:

请注意,如果你写了这样的东西,你会得到一个类型错误:

interface myProps {
   name: string;
   clickFunction: () => void;
}

回答by suku

this method worked for me:

这种方法对我有用:

The parent:

家长:

 class App extends React.Component<Props, State> {
   greet() {
    alert('Hello!')
   }
   render() {
      return (
       <div className="col-xs-10 col-xs-offset-1">
        <Home greet={this.greet}/>
       </div>
     ) 
   }
}

The child:

孩子:

interface Props {
  greet: () => void
}

export class Home extends React.Component<Props, State> {
 constructor(props: any) {
   super(props)
 }

 render() {
   return (
    <button className="btn btn-warn" onClick={this.props.greet}>Greet</button>
   )
 }
}