将诸如Onchange和OnClick之类的参数传递给与TypeScript的React组件

发布于 2025-02-08 12:44:51 字数 343 浏览 3 评论 0原文

我正在尝试使用React创建一个页面,因为我正在使用Typescript。

在项目中,有一个组件是一个输入错误,如何正确传递onChange?我知道如何使用JavaScript进行操作,但不使用Typescript进行操作。

我将代码如下:

import { StyledInput } from "./Input.styles";

export const Input = ( { onChange } ) => {
    return(
        <StyledInput onChange={onChange}/>
    )
}

I'm trying to create a page with react, for that I'm using typescript.

In the project there is a component that is an input and in it I want there to be an onChange function, but when I put it in the component, it has a red dash, indicating that there is an error, how could I pass the onChange correctly? I know how to do it using javascript, but not with typescript.

I made the code as follows:

import { StyledInput } from "./Input.styles";

export const Input = ( { onChange } ) => {
    return(
        <StyledInput onChange={onChange}/>
    )
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捶死心动 2025-02-15 12:44:51

您需要定义道具类型,例如

export const Input = ( { onChange }:{ onChange:(x:string)=>void } ) => {

或更准确地说,

type Props ={ onChange:React.ComponentProps<typeof<StyledInput>>['onChange'] }
export const Input = ( { onChange }:Props ) => {

此方法可确保如果您是第三方包裹类型的签名更改,则仍然具有在道具中定义的相同精确类型

You need to define the prop type, e.g.

export const Input = ( { onChange }:{ onChange:(x:string)=>void } ) => {

Or more precisely

type Props ={ onChange:React.ComponentProps<typeof<StyledInput>>['onChange'] }
export const Input = ( { onChange }:Props ) => {

This approach ensures that if you're 3rd party package type signature changes you still have the same precise type defined in your props

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文