您如何将其他道具传递给React中的功能组件?

时间:2020-02-28 15:33:13

标签: reactjs typescript

  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)

如果我将子级用作参数,似乎不能仅以常规方式添加参数。我该怎么做我打算做什么?

2 个答案:

答案 0 :(得分:1)

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

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

从道具中提取属性children,并为您提供任何其他道具作为对象props

然后您可以像使用它一样

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

答案 1 :(得分:0)

好吧,您必须定义道具类型

type TodoCotextProviderProps {
 children: React.ReactNode,
  // any aditional props you might have
}

以及组件的符号

export function TodosContextProvider(props: TodoCotextProviderProps  )