【问题标题】:Passing a function as a prop to a Typescript React Functional Component将函数作为道具传递给 Typescript React 功能组件
【发布时间】:2020-03-12 19:28:57
【问题描述】:

我有一个功能组件(用 Typescript 编写)需要将处理程序函数向下传递给子组件。这是父函数的缩小版:

type Props = { handleLocationChange(): void };

const Sidebar: React.FC<Props> = (props) => { 
 const handleLocationChange = () => {
    console.log('Location Changed.');
  };
return (
   <>
      <Search handleLocationChange={handleLocationChange} /> 
   </>
)
}

在 VS Code 中,搜索组件显示错误:

输入 '{ handleLocationChange: () => void; }' 不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }'。 类型“IntrinsicAttributes & { children?: ReactNode;”上不存在属性“handleLocationChange” }'.ts(2322)

任何帮助将不胜感激。我确定我错过了一些小东西。

【问题讨论】:

  • 我认为您不能在定义时调用该函数。尝试不调用函数:{ handleLocationChange: void }

标签: javascript reactjs typescript react-props react-functional-component


【解决方案1】:

将你的处理程序编码为函数,这样

function handleLocationChange(){
    console.log('Location Changed.');
  };

那么它应该可以工作

【讨论】:

  • 这是功能组件内部的功能。我不相信你可以这样声明函数。
【解决方案2】:

您需要将 handleLocationChange 声明为 Search 组件上的一个道具

【讨论】:

  • 这应该是一条评论
  • 您为侧边栏声明了type Props,这是错误的组件。而是在您的搜索组件上声明 type Props。这需要句柄 locationChange 作为道具。您有一个 typeError 因为 Search 正在接收它无法识别的道具。搜索不会根据类型声明进行 locationChange。
【解决方案3】:

您需要在 Search Component 中声明 prop 类型,并将 type 声明为参数:

//use this type to both components (children and parent)
interface FuncProps {
    //here you can declare the return type (here is void)
    handleLocationChange: (values: any) => void;
}
//children start
// here are the tip, define the type in the React.FC and in the FC's parameters itself
const Search: React.FC<FuncProps> = (props: FuncProps) => {
    ... your component behavior and view ...
    return (
        {/*↓↓↓↓ use the prop like this ↓↓↓↓*/}
        <input onClick={props.handleLocationChange('something if you need')}/>
    )
};
//children end

// parent start
const Sidebar: React.FC<Props> = (props: FuncProps) => { 
return (
   <>
      <Search handleLocationChange={props.handleLocationChange} /> 
   </>
)
}
//parent end

我希望这个答案可以帮助那些想要使用打字稿并希望通过组件轻松传递函数的人(我不建议通过多个级别传递函数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多