[英]Exporting functional and class components in React
我在VS Code中使用的是ES7 React / Redux / GraphQL / React-Native代碼片段 ,我不確定導出使用哪種“類型”。 如果要導出,則應在類/功能組件聲明或文件末尾。
在下面的代碼中,我有2個類組件導出和3個功能組件導出。
建議使用以下哪項?
// ****************************************
// 1. rcc
// ****************************************
import React, { Component } from 'react'
export default class myComponent extends Component {
render() {
return (
<div>
</div>
)
}
}
// ****************************************
// 2. rce
// ****************************************
import React, { Component } from 'react'
class myComponent extends Component {
render() {
return (
<div>
</div>
)
}
}
export default myComponent
// ****************************************
// 3. rfc
// ****************************************
import React from 'react'
export default function myComponent() {
return (
<div>
</div>
)
}
// ****************************************
// 4. rfce
// ****************************************
import React from 'react'
function myComponent() {
return (
<div>
</div>
)
}
export default myComponent
// ****************************************
// 5. rafc
// ****************************************
import React from 'react'
const myComponent = () => {
return (
<div>
</div>
)
}
export default myComponent
我的第二個問題是關於功能組件的-最好(建議)將功能組件編寫為箭頭函數或經典函數聲明?
非常感謝!
丹·阿布拉莫夫(Dan Abramov)在推文中說:
JS技巧:無論您喜歡哪種導出樣式(默認或命名)或使用哪種函數樣式(箭頭或聲明),請確保您的函數具有名稱! 對於React組件在DevTools中顯示的名稱和警告尤其重要。
而且,使用之間rce
和rcc
導出類組件:這取決於你不過來決定,在CRA文檔rce
用於:
import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file
class DangerButton extends Component {
render() {
return <Button color="red" />;
}
}
export default DangerButton;
使用這種樣式,您可以輕松地使用HOC ,在本示例中,我們希望將類組件轉換為庫提供的高階組件:
import { injectIntl} from "react-intl";
class Button extends React.Component {
render() {
const intl = this.props.intl;
const title = intl.formatMessage({
id: "button.title",
defaultMessage: "Hello!"
});
return <Button title={title}>...</Button>;
}
}
export default injectIntl(Button);
在使用功能組件與類組件之間:請參考文檔 ,功能組件更易於編寫和測試,現在有了React的useState
鈎子,您就可以在功能組件中使用狀態。 對於類組件,請閱讀React.Component文檔。
如果要導出文件中的多個組件,則僅需使用export ComponentName
(無默認值)。
然后您可以導入為
import {ComponentA,ComponentB,...} from '../directory'
另一種情況是您只能將文件中的一個組件導出為
export default Class extends ........{} //
要么
export default Class; // at the end of file
兩者都一樣。
您可以使用任何名稱導入
import Class from '../directory'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.