【问题标题】:How to pass a function as an argument to a ReactJS component in TypeScript如何将函数作为参数传递给 TypeScript 中的 ReactJS 组件
【发布时间】:2016-05-23 23:32:54
【问题描述】:

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

下面是调用组件的代码:

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

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

这里是我要编写的组件:

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.

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:
    <MyButton name="My Button" clickFunction={MyPublicFunction(1)} >
    

    表达式MyPublicFunction(1) 在包含表达式的求值过程中被立即调用。你想要的是向clickFunction提供一个函数

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

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

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

    【讨论】:

    • 好答案。我只是希望语法不必看起来那么奇怪。
    【解决方案2】:

    这个方法对我有用:

    父母:

     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>
         ) 
       }
    }
    

    孩子:

    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>
       )
     }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 2012-12-07
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2021-06-03
      相关资源
      最近更新 更多