gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:39 24 4
gpt4 key购买 nike

我正在尝试制作一个可重用的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com