react如何给组件默认值
设置默认 Props
在 React 中,可以通过 defaultProps 属性为组件设置默认值。这种方式适用于类组件和函数组件(通过 .defaultProps 属性)。
class MyComponent extends React.Component {
render() {
return <div>{this.props.name}</div>;
}
}
MyComponent.defaultProps = {
name: "Default Name"
};
函数组件默认参数
对于函数组件,可以使用 ES6 默认参数语法直接为 props 设置默认值:
function MyComponent({ name = "Default Name" }) {
return <div>{name}</div>;
}
默认 Props 与 TypeScript
在 TypeScript 中,可以通过接口定义 props 并设置默认值:
interface Props {
name?: string;
}
function MyComponent({ name = "Default Name" }: Props) {
return <div>{name}</div>;
}
默认 Children
对于 children 的默认值,可以通过条件渲染实现:
function MyComponent({ children }) {
return <div>{children || "Default Content"}</div>;
}
默认状态值
对于组件内部状态,可以在构造函数或 useState 中设置默认值:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}
function MyComponent() {
const [count, setCount] = useState(0);
}
合并默认 Props
当需要深度合并默认 props 时,可以使用工具如 lodash 的 _.defaultsDeep:
const defaultProps = {
config: {
color: "blue",
size: "medium"
}
};
function MyComponent(props) {
const mergedProps = _.defaultsDeep(props, defaultProps);
}






