我已經探索reactjs並注意到定義elemens/components的兩種方法。函數方法和分類方法在reactjs中的區別
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
};
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
和功能的方法:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
他們在結果方面是相同的。但功能appracoh至少對我來說更清潔。
什麼帶來的分級方法:從reactjs文檔:
這讓我們使用額外的功能,如本地狀態和生命週期掛鉤。
除了狀態,純粹的功能方法分類的生命週期鉤子還有更多優勢嗎?
何時使用哪一個?
第一種方法更像是其他面嚮對象語言,使用起來更清晰。您可以嘗試使用這兩種方法制作複雜的組件,並查看哪個更清潔 –