reactjs - 在 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)
如果我使用孩子作为论点,似乎我不能以传统方式添加论点。我该如何做我打算做的事?
解决方案
组件的第一个参数是 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>
推荐阅读
- javascript - 在画布中加入带圆圈的线条
- sed - 使用 sed 删除文件中的空行
- javascript - reactjs中的选择框向我显示警告为“警告:使用`defaultValue`或`value`道具
- python - newdf = pd.concat([df1,df2],axis = 0),现在newdf的每一行都是一个DataFrame?
- angularjs - 在 django {% static %} 标签内使用 Angular js 模板
- node.js - 显示错误的firebase函数无法读取未定义的先前属性
- unix - 当 read() 时 timerfd 神秘地将 int 设置为 0
- stripe-payments - 如何在 Stripe 中发送虚拟 webhook?
- c# - 使用 Refit 添加自定义 TypedClient
- python - 根据字符拆分列表的元素