首页 > 解决方案 > 在 React 中,如何将额外的 props 传递给功能组件?

问题描述

  export function TodosContextProvider( {children}: {children: React.ReactNode}, props: any) {
    const [todos, dispatch] = React.useReducer(todosReducer, [
      {
        Id: 1,
        Title: 'Learn Context API',
        Done: true
      },
      {
        Id: 2,
        Title: 'Learn TypeScript',
        Done: true
      },
      {
        Id: 3,
        Title: 'Use Context API with TypeScript',
        Done: false
      }
    ]);

    console.log(props.siteUrl);
    return (
      <TodosDispatchContext.Provider value={dispatch}>
        <TodosStateContext.Provider value={todos}>
          {children}
        </TodosStateContext.Provider>
      </TodosDispatchContext.Provider>
    );
  }

我有这个 TodosContextProvider,我编写了它,然后添加了一个名为 props 的附加参数,希望我可以将一些附加参数从根类传递给我的函数组件。

export default class Crud extends React.Component<ICrudProps, {}> {
  public render(): React.ReactElement<ICrudProps> {

    return (
      <TodosContextProvider props={this.props}>
        <TodoForm />
        <TodoList />
      </TodosContextProvider>
    );
  }
}

我做了以下操作并将 this.props 传递给 props 以记录它并查看来自 TodosContextProvider 的内容,但这会引发错误。

Type '{ children: Element[]; props: Readonly<ICrudProps> & Readonly<{ children?: ReactNode; }>; }' is not assignable to type 'IntrinsicAttributes & { children: ReactNode; }'.
  Property 'props' does not exist on type 'IntrinsicAttributes & { children: ReactNode; }'.ts(2322)

如果我使用孩子作为论点,似乎我不能以传统方式添加论点。我该如何做我打算做的事?

标签: reactjstypescript

解决方案


组件的第一个参数是 props。children始终只是该对象的一个​​属性。React 会自动将它添加到 props 中,无论你在组件的开始标签和结束标签之间放置什么。如果您想访问所有其他属性,props可以使用扩展运算符。将您的函数签名更改为:

export function TodosContextProvider( {children, ...props}: {children: React.ReactNode, [x: string]: any}) { /* ... */}

这会从 props中提取属性children,并为您提供任何其他 props 作为 object props

然后你可以像这样使用它:

<TodosContextProvider foo="bar" {...this.props}>
    {/* ... */}
</TodosContextProvider>

推荐阅读