在 React TypeScript 中使用默认值设置可选项
作者:迹忆客
最近更新:2022/06/05
浏览次数:
在 React TypeScript 中使用默认值设置可选项:
- 使用问号将类型上的属性标记为可选。
- 在函数的定义中解构它们时,为属性提供默认值。
interface EmployeeProps {
name?: string; // 👈️ 标记为可选
age?: number; // 👈️ 标记为可选
country: string; // 👈️ 必选项
}
function Employee({name = 'Alice', age = 30, country}: EmployeeProps) {
return (
<div>
<h2>{name}</h2>
<h2>{age}</h2>
<h2>{country}</h2>
</div>
);
}
export default function App() {
return (
<div>
<Employee name="Bob" age={29} country="Belgium" />
<hr />
<Employee country="Austria" />
</div>
);
}
我们将 name 和 age 属性标记为可选。
这意味着组件可以在提供或不提供 name 和 age 属性的情况下使用。\
如果未指定可选属性的值,则将其设置为 undefined 。
不为 prop 提供值和将 prop 设置为 undefined 的值是相同的。
我们还在 Employee 组件的定义中为 name 和 age 参数设置了默认值。
function Employee({name = 'Alice', age = 30, country}: EmployeeProps) {
return (
<div>
<h2>{name}</h2>
<h2>{age}</h2>
<h2>{country}</h2>
</div>
);
}
对象中的 name 属性默认设置为 Alice,所以如果没有提供 name 属性,它将被分配一个 Alice 的值。
我们还可以通过将其所有属性标记为可选来将整个 props 对象设置为可选。
interface EmployeeProps {
name?: string; // 👈️ 所有的标记为可选项
age?: number;
country?: string;
}
function Employee({
name = 'Alice',
age = 30,
country = 'Austria',
}: EmployeeProps) {
return (
<div>
<h2>{name}</h2>
<h2>{age}</h2>
<h2>{country}</h2>
</div>
);
}
export default function App() {
return (
<div>
<Employee name="Bob" age={29} country="Belgium" />
<hr />
<Employee />
</div>
);
}
EmployeeProps
类型中的所有属性都标记为可选,因此无需提供任何属性即可使用该组件。
我们为 Employee
组件的所有 props 设置了默认值,因此如果省略任何 props,则使用默认值。