[英]Strange using React stateless components
有沒有人知道將無狀態組件用於大型組件的原因,其中定義了變量等方法。我最近加入了使用這種方法的項目。 我很困惑。
我想最好使用小組件,但仍然
也許對此有一些合乎邏輯的解釋,例如性能等。
簡單的代碼示例:
const myComponent = ({p1, p2, p3}) => {
const buttonProps = {
className: 'button',
onClick: () => { console.log('clicked'); }
};
const getButtonName = () => 'Submit';
const getButton = () => {
return (
<button ...buttonProps>{getButtonName()}<button>
);
}
/* a lot of defined objects like above */
return (
<div>
{getButton()}
</div>
);
}
主要問題是為什么使用 getButton() 之類的方法而不是創建 MyButton 組件。 我想這很容易理解,調試等。
擴展 React.Component 的有狀態組件有很多附加功能。 您基本上是在導入 React.Component 中內置的所有變量和函數,例如生命周期函數。 如果你不需要它們,那么 stateless 只會創建一個更輕的組件。 例如,當您的組件掛載時,有狀態的組件將調用 componentDidMount(),但無狀態的組件甚至沒有 componentDidMount()。
編輯:回答您更具體的問題:該函數類型是一個組件,一個功能組件,可重用,但在功能組件的渲染函數中,無法使用 <> 語法調用該組件。 它位於另一個組件內,因此它的作用域僅限於父組件,並且可以訪問 props。 它有點基於意見,因為使用一種組件而不是另一種組件只是在可讀性、可重用性和功能之間取得平衡。
在 React 中,您可以擁有基於類的組件或基於函數的組件(功能組件)。
功能組件通常更容易測試和理解,而且它們更輕。
React 世界的趨勢是基於函數的組件。 在過去一年左右的時間里,情況更是如此,隨着鈎子(即useState
、 useEffect
等)的引入,它允許您擁有一個輕量級的功能組件,但可以訪問基於類的東西組件他們的額外能力。
基於類的組件本身並沒有什么問題,但趨勢是遠離它們,所以聽到你說你加入了一個不使用它們的項目,我並不感到驚訝。
你可能對 2018 年開始介紹 hooks 的 React Conf 視頻之一感興趣: React Conf 2018相關部分大約在 11:30 開始。
stateless component
意味着它沒有state
,您示例中的React
組件將被視為functional component
。 至於模式本身,它也可以在class component
實現——它不僅僅針對functional components
。
例如,上面的代碼可以像下面這樣編寫,它會產生完全相同的結果:
class MyComponent extends React.Component {
render() {
const buttonProps = {
className: `button`,
onClick: () => {}
}
const getButtonName = () => `Submit`
const getButton = () => {
return (
<button {...buttonProps}>{getButtonName()}</button>
)
}
return (
<div>{getButton()}</div>
)
}
}
我不知道上下文,因此很難弄清楚為什么要這樣做 - 最好詢問負責選擇以這種方式編寫組件的開發人員以找出原因。
不幸的是,或者幸運的是, React
沒有固執己見,人們可以隨心所欲地做任何事情,這可能會導致“奇怪”的模式並不總是好的。
您提供的代碼片段創建了乍一看不清楚的不必要的抽象 - 我必須弄清楚getButton
作用,然后轉到getButtonName
以查看button
元素內部呈現的內容,然后我不得不搜索buttonProps
來計算找出正在傳遞的props
。
如果你真的需要一個可重用的函數來返回一個組件,那為什么不直接用“ React
”的方式來做呢?
function Button({ children, ...rest }) {
const defaultProps = {
className: `button`,
onClick: () => {}
}
const props = { ...defaultProps, ...rest }
return (
<button {...props}>
{children}
</button>
)
}
然后,回到您的示例,可以在以下示例中使用:
// by the way, start with an uppercase when naming React components
const MyComponent = ({ p1, p2, p3 }) => {
return (
<div>
<Button>I am a button #1!</Button>
<Button
onClick={() => console.log(`HelloWorld`)}
>
I am a button #2 with a custom `onClick` handler!
</Button>
</div>
)
}
這種方法更好更干凈,所以正如你在評論中建議的那樣, getButton
應該寫成一個實際的React
組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.