本文介绍了反应功能组件默认道具与默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在React 功能组件中,这是使用Component.defaultProps或在函数定义上使用默认参数设置默认道具的更好方法,例如:
In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameters on the function definition, examples:
默认道具:
const Component = ({ prop1, prop2 }) => ( <div></div> ) Component.defaultProps = { prop1: false, prop2: 'My Prop', }默认参数:
const Component = ({ prop1 = false, prop2 = 'My Prop' }) => ( <div></div> )推荐答案
通常(ES6),第二种方法更好.
In general (ES6), the second way is better.
在特定情况下(在React上下文中),第一个更好,因为它是组件生命周期中的一个主要阶段,即初始化阶段.
In specific (in React context), the first is better since it is a main phase in the component lifecycle, namely, the initialization phase.
请记住,ReactJS是在ES6之前发明的.
Remember, ReactJS was invented before ES6.
更多推荐
反应功能组件默认道具与默认参数
发布评论