gpt4 book ai didi

typescript - typescript 3.33的onClick问题并使用react

转载 作者:行者123 更新时间:2023-12-04 00:27:18 25 4
gpt4 key购买 nike

我正在尝试在带有 TypeScript 和 React 的链接上使用 onClick 属性:

import * as React from 'react';
import { any } from 'prop-types';

function handleClick(this:any,name:React.ReactNode) {
console.log('The link was clicked.');
this.props.callbackFromParentSearch(name);
}

export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={handleClick(r.name)}>
<li key={r.id}>

{r.name}

</li>
</a>
))
return <ul>{options}</ul>
}

export default Suggestions

但这给出了一个错误:

Type 'void' is not assignable to type '(event: MouseEvent) => void'.ts(2322) index.d.ts(1315, 9): The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps, HTMLAnchorElement>'



那么如何在 TypeScript & React 中正确使用 onClick 事件呢?

最佳答案

您需要传递一个函数:

onClick={() => handleClick(r.name)}

但是,即使这样,您的代码也无法正常工作,因为您的 handleClick函数需要以 this 的方式绑定(bind)是一个包含你的 Prop 的对象。在您的代码中并非如此。

您的组件应该像这样工作:
export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={() => props.callbackFromParentSearch(r.name)}>
<li key={r.id}>

{r.name}

</li>
</a>
))
return <ul>{options}</ul>
}

或像这样:
function handleClick(props: any, name: React.ReactNode) {
console.log('The link was clicked.');
props.callbackFromParentSearch(name);
}

export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={() => handleClick(props, r.name)}>
<li key={r.id}>

{r.name}

</li>
</a>
))
return <ul>{options}</ul>
}

关于typescript - typescript 3.33的onClick问题并使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206526/

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