我正在尝试制作一个可重用的 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.
最佳答案
<MyButton name="My Button" clickFunction={MyPublicFunction(1)} >
表达式 MyPublicFunction(1)
在计算包含表达式的过程中立即被调用。您想要的是为 clickFunction
提供一个函数:
<MyButton name="My Button" clickFunction={() => MyPublicFunction(1)} >
请注意,如果您编写如下内容,将会出现类型错误:
interface myProps {
name: string;
clickFunction: () => void;
}
关于reactjs - 如何将函数作为参数传递给 TypeScript 中的 ReactJS 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369013/