• react中怎么为props设置默认值


    在这里插入图片描述
    在React中,你可以使用ES6的类属性(class properties)或者函数组件中的默认参数(default parameters)来定义props的默认值。

    1.类组件中定义默认props

    对于类组件,你可以在组件内部使用defaultProps属性来定义默认的props值:

    class MyComponent extends React.Component {
      render() {
        return <div>{this.props.name}</div>;
      }
    }
    
    MyComponent.defaultProps = {
      name: 'Default Name'
    };
    

    这样,如果name属性没有被传递给MyComponent,它将默认使用'Default Name'

    2.函数组件中定义默认props

    对于函数组件,你可以使用参数默认值来定义props的默认值:

    function MyComponent({ name = 'Default Name' }) {
      return <div>{name}</div>;
    }
    

    在这个例子中,如果name没有被传递,它将默认为'Default Name'

    3.使用React.Component的子类

    如果你在使用React.Component作为基类来创建组件,你可以在构造函数中设置默认props:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
    
      render() {
        return <div>{this.props.name}</div>;
      }
    }
    
    MyComponent.defaultProps = {
      name: 'Default Name'
    };
    

    4.使用Hooks的函数组件

    对于使用Hooks的函数组件,你仍然可以使用默认参数,也可以获取到children:

    function MyComponent({ name = 'Default Name',children="" }) {
      // 使用Hooks
      // 获取props中的children
      return (
         <div>
             <h2>{name}</h2>
             <div>{childrdn}</div>
         </div>
      );
    }
    
  • 相关阅读:
    typedef的用法——c语言
    PMP考试3A通过学员:如何备考PMP?
    Go 语言中的 Cond 机制详解
    Hbase集群搭建
    【已解决】socket.gaierror: [Errno -3] Temporary failure in name resolution
    Vue+springboot银首饰商城销售系统java
    重复造轮子 SimpleMapper
    git clone访问github失败
    字节青训营 浅尝Type Script
    三、N元语法(N-gram)
  • 原文地址:https://blog.csdn.net/sky6862/article/details/139061882