简体   繁体   English

React,使用 TypeScript 将状态设置器(useState)传递给子组件

[英]React, passing state setter (useState) to child component with TypeScript

I'm having a hard time figuring out the types when passing the useState setter function to a child component.将 useState setter 函数传递给子组件时,我很难弄清楚类型。

I've tried to simplify to just the essential code below:我试图简化为下面的基本代码:

parent父母

function Parent() {    
  const [name, setName] = useState("Structured")
  ..
  return (
    <>
      <Child setName={setName}/>
    </>

child孩子

import { Dispatch, SetStateAction } from "react";

function Child(setName: Dispatch<SetStateAction<string>>){
  return (
    <>
      <Input onChange={
        (value)=>{
          setName(value: SetStateAction<string>)
          console.log(value)
        }
      </Input>
    </>

On the parent I'm getting the following errors:在父母身上,我收到以下错误:

Type "{ setName: Dispatch<SetStateAction>; }' is not assignable to type ' IntrinsicAttributes & Dispatch<SetStateAction' Property 'setName' does not exist on type 'IntrinsicAttributes & Dispatch<SetStateAction>'.类型“{ setName: Dispatch<SetStateAction>; }”不可分配给类型“IntrinsicAttributes & Dispatch<SetStateAction”属性“setName”在类型“IntrinsicAttributes & Dispatch<SetStateAction>”上不存在。

On the child I'm getting:关于我得到的孩子:

Argument of type "string | string[]' is not assignable to parameter of type 'SetStateAction' Type "string[]' is not assignable to type "SetStateAction' “string | string[]”类型的参数不可分配给“SetStateAction”类型的参数 类型“string[]”不可分配给“SetStateAction”类型

Should be应该

function Child({ setName } : { setName: Dispatch<SetStateAction<string>>}){

Child component accepts props, which is an object, not just setName value Child组件接受 props,它是一个对象,而不仅仅是setName

You could type your React functional component with the help of FC from React, if you wanna a fully React component.如果你想要一个完整的 React 组件,你可以在 React 的FC的帮助下键入你的 React 功能组件。 If not, for example you cannot access children form props , as it is not known as a React component.如果不是,例如你不能访问children表单props ,因为它不被称为 React 组件。

For the onChange part I'm a doing a cast for now as I don't know how this Input look like.对于onChange部分,我现在正在做演员,因为我不知道这个Input的样子。 Can you show it ?你能展示一下吗?

import { Dispatch, SetStateAction, FC} from "react";

interface ChildPropsType {
  setName: Dispatch<SetStateAction<string>>
}
/* 
   I'm using an interface for convenience, you can 
   replace it with { setName: Dispatch<SetStateAction<string>> }
*/
const Child : FC<ChildPropsType> = ({setName}) => {
  return (
    <>
      <Input onChange={
        (value as string)=>{
          setName(value);
        }
      </Input>
    </>
  )
}
export default Child;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM