React 中的 Props 允许我们在不同的组件之间传递数据和参数,这些数据和参数可以流过 React 中的整个组件树。传递给不同组件的 props 可以具有定义为基本类型或用户定义类型的固定类型,就像在 TypeScript 中一样。
本篇文章将演示如何将 React 的可选 props 与默认值一起使用。
TypeScript 中的可选属性
在 TypeScript 中,可以使用
?
将类型或属性设为可选操作符。这个事实可以用来在 React 中传递可选参数。
interface
OptionalComponentProps {
color? :
string
;
title :
string
;
size? :
number
;
在上面的示例中,包含特定组件的 props 的类型定义,
color
和
size
属性被定义为可选的。
interface
Props {
color? :
string
;
size:
number
;
title? :
string
;
function
Card(props :
Props
){
const
{ color , size, title}
=
props;
return
(
<
div
>{color}</
div
>
<
div
>{size}</
div
>
<
div
>{title}</
div
>
</
div
>
function
App() {
return
(
<
Card
size
=
{
20
}
title
=
"Cool card"
/>
</
div
>
因此在上面的例子中,父组件是
App
,
Props
类型的 props 被传递给
Card
组件。
color
和
title
属性由
?
标记为可选操作符。
如果可选属性没有作为 prop 传递给组件,它会被初始化为
undefined
,因此不会显示或呈现。
TypeScript 中具有默认值的可选属性
上面的示例也可以与组件提供的默认值一起使用。
interface
Props {
color? :
string
;
size:
number
;
title? :
string
;
function
Card(props :
Props
){
const
{ color
=
'red'
, size, title
=
'Default title'
}
=
props;
return
(
<
div
>{color}</
div
>
<
div
>{size}</
div
>
<
div
>{title}</
div
>
</
div
>
function
App() {
return
(
<
Card
size
=
{
20
}
title
=
"Cool card"
/>
</
div
>
早些时候,
color
属性没有被渲染,因为没有默认值,但现在因为没有值作为 props 传递,所以使用默认值来渲染组件。但是,没有使用
title
属性的默认值,因为它被传递给组件的 prop 覆盖。
在 React 中使用
defaultProps
属性来设置 Props 的默认值
React 支持为使用
defaultProps
属性传递的道具分配默认值。渲染组件时可以直接分配和使用默认值。
interface
Props {
color? :
string
;
size:
number
;
title? :
string
;
const
defaultProps :
Props
=
{
color
:
"red"
,
size :
20
,
title
:
"A cool title"
function
Card(props :
Props
){
return
(
<
div
>{props.color}</
div
>
<
div
>{props.size}</
div
>
<
div
>{props.title}</
div
>
</
div
>
Card.defaultProps
=
defaultProps;
function
App() {
return
(
<
Card
size
=
{
20
}
title
=
"Cool card"
/>
</
div
>
Java Struts2 框架 java.lang.NoSuchFieldError: EMPTY_BYTE_ARRAY 错误解决
PHP扩展开发 ini配置项定义
php zookeeper你需要知道的细节
PHP操作redis的两种方式
PHP简体转繁体——MediaWiki-zhconvert
PHP7 中 include、require 相对于PHP5你所不知道的一些
Python 错误 IsADirectoryError: [Errno 21] Is a directory 解决方法
PHP——json_encode中文编码问题
PHP重写session机制