[英]How to add props to the component using typescript and react?
i have a Parent Component and i pass RouteComponentprops like below,我有一个父组件,我通过 RouteComponentprops 如下所示,
function Parent({ history }: RouteComponentProps) {
//some logic
}
Now i want to add a prop OpenByDefault to the Parent component like below,现在我想向父组件添加一个道具 OpenByDefault,如下所示,
interface Props {
OpenByDefault?: boolean;
}
function Parent({OpenByDefault = false}: Props) {
//some logic
}
i am not sure how to add {history: RouteComponentProps} to this Props as well.I am new to using typescript.我也不确定如何将 {history: RouteComponentProps} 添加到此道具中。我是使用 typescript 的新手。 could someone help me with this.
有人可以帮我解决这个问题。 thanks.
谢谢。
You have at least two options:你至少有两个选择:
RouteComponentProps
when defining Props
Props
时扩展RouteComponentProps
Here's an example of #1:这是#1的示例:
interface Props extends RouteComponentProps {
OpenByDefault?: boolean;
}
Then use Props
instead of RouteComponentProps
on Parent
:然后在
Parent
上使用Props
而不是RouteComponentProps
:
function Parent({ history, OpenByDefault }: Props) {
// ...
}
Here's an example of #2:这是#2的示例:
function Parent({ history, OpenByDefault }: RouteComponentProps & Props) {
// ...
}
RouteComponentProps & Props
means that the parameter Parent
accepts is a combination of both RouteComponentProps
and Props
. RouteComponentProps & Props
意味着Parent
接受的参数是RouteComponentProps
和Props
的组合。
Since you say you're new to this stuff: By convention, OpenByDefault
should be called openByDefault
(lower case initial letter).既然你说你是这个东西的新手:按照惯例,
OpenByDefault
应该被称为openByDefault
(小写首字母)。 In JavaScript and TypeScript, an initial capital letter is almost only ever used for constructor function names.在 JavaScript 和 TypeScript 中,首字母大写几乎只用于构造函数 function 名称。 (In React it's also used for component functions, even when they aren't constructors.)
(在 React 中,它也用于组件函数,即使它们不是构造函数。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.