【问题标题】:How to pass in props in react directly as constants?如何在反应中直接作为常量传递道具?
【发布时间】:2021-10-08 06:59:38
【问题描述】:

如何在 props 中编写类型,这些类型直接作为常量传递,例如const ComponentName = ({tasks: TaskType[]}) => {return (<>{tasks[0]}</>)}?

我的 TaskType 作为接口存储在另一个文件中。我不想使用道具并直接写下每个道具的名称,但打字稿给了我很多错误。

文件可以在这里找到https://codesandbox.io/s/great-pare-m8ei2?file=/src/App.tsx

【问题讨论】:

  • 如果我正确理解了这个问题,这与 reactjs 几乎没有关系,而与打字稿中的参数语法有关。

标签: reactjs typescript


【解决方案1】:

键入功能组件的正确方法是使用 react 中的 React.FC 类型。像这样的东西:

const AddTaskForm: React.FC<{tasks: TaskType[], setTasks: React.Dispatch<React.SetStateAction<TaskType[]>>}> = ( {tasks, setTasks} ) => {
...
}

export default AddTaskForm;

【讨论】:

    【解决方案2】:

    这是一个让类型接近参数的解决方案

    (_: {
      tasks: TaskType[],
      setTasks: React.Dispatch<React.SetStateAction<TaskType[]>>
    })
    

    需要注意的是,这种语法对于 typescript 函数参数是全局的,与 ReactJS 没有什么特别的关系

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2020-11-27
      • 2020-07-28
      相关资源
      最近更新 更多