[英]React functional component default props vs default parameters
在 React功能組件中,這是設置默認道具的更好方法,使用Component.defaultProps
或使用 function 定義中的默認參數,示例:
默認道具:
const Component = ({ prop1, prop2 }) => (
<div></div>
)
Component.defaultProps = {
prop1: false,
prop2: 'My Prop',
}
默認參數:
const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (
<div></div>
)
功能組件上的defaultProps
最終將被棄用(根據核心團隊之一丹·阿布拉莫夫的說法) ,因此為了面向未來,值得使用默認參數。
一般來說(ES6),第二種方式更好。
具體來說(在 React 上下文中),第一個更好,因為它是組件生命周期中的一個主要階段,即初始化階段。
請記住,ReactJS 是在 ES6 之前發明的。
第一個可能會導致一些難以調試的性能問題,尤其是在您使用 redux 時。
如果您正在使用對象、列表或函數,那么這些將是每次渲染時的新對象。 如果您有復雜的組件來檢查組件身份以查看是否應該進行重新渲染,這可能會很糟糕。
const Component = ({ prop1 = {my:'prop'}, prop2 = ['My Prop'], prop3 = ()=>{} }) => {(
<div>Hello</div>
)}
現在工作正常,但是如果您有更復雜的組件和狀態,例如帶有數據庫連接和/或 react useffect 鈎子的 react-redux 連接組件,以及組件狀態,這可能會導致大量重新渲染。
單獨創建默認道具對象通常是更好的做法,例如。
const Component = ({prop1, prop2, prop3 }) => (
<div>Hello</div>
)
Component.defaultProps = {
prop1: {my:'prop'},
prop2: ['My Prop'],
prop3: ()=>{}
}
或者
const defaultProps = {
prop1: {my:'prop'},
prop2: ['My Prop'],
prop3: ()=>{}
}
const Component = ({
prop1 = defaultProps.prop1,
prop2 = defaultProps.prop2
prop3 = defaultProps.prop3
}) => (
<div>Hello</div>
)
無恥的插件在這里,我是 with-default-props 的作者。
如果您是 TypeScript 用戶, with-default-props可能會對您有所幫助,它使用高階函數來提供正確的組件定義,並提供給定的 defaultProps。
例如。
import { withDefaultProps } from 'with-default-props'
type Props = {
text: string;
onClick: () => void;
};
function Component(props: Props) {
return <div onClick={props.onClick}>{props.text}</div>;
}
// `onClick` is optional now.
const Wrapped = withDefaultProps(Component, { onClick: () => {} })
function App1() {
// ✅
return <Wrapped text="hello"></Wrapped>
}
function App2() {
// ✅
return <Wrapped text="hello" onClick={() => {}}></Wrapped>
}
function App3() {
// ❌
// Error: `text` is missing!
return <Wrapped onClick={() => {}}></Wrapped>
}
甚至你可能會問,為什么不使用下面的代碼和props || value
props || value
而不是defaultProps
:
class SomeComponent extends React.Component {
render() {
let data = this.props.data || {foo: 'bar'}
return (
<div>rendered</div>
)
}
}
// SomeComponent.defaultProps = {
// data: {foo: 'bar'}
// };
ReactDOM.render(
<AddAddressComponent />,
document.getElementById('app')
)
但請記住defaultProps
使代碼更具可讀性,特別是如果您有更多的props
並使用||
控制它們運算符可能會使您的代碼看起來很丑
這是關於棄用defaultProps
的官方公告。
您可以使用解構方法,例如:
const { inputFormat = 'dd/mm/yyyy', label = 'Default Text', ...restProps } = props;
我不知道是否是最好的方法,但它有效:)
export interface ButtonProps {
children: ReactNode;
type?: 'button' | 'submit';
}
const Button: React.FC<ButtonProps> = ({ children, type = 'button' }) => {
return (
<button type={type}
>
{children}
</button>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.