1. 함수 스프리팅
A. 스프리팅을 사용안함
src/App.js
import React, { Component } from 'react';
import notify from './notify';
class App extends Component {
handleClick = () => {
notify();
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default App;
src/notify.js
function notify() {
alert('종소리 울려라 종소리 울려~');
}
export default notify;
B. Dynamic Import를 이용한 함수 스프리팅
src/App.js
import React, { Component } from 'react';
class App extends Component {
handleClick = () => {
import('./notify').then(({ default: notify }) => {
notify();
});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default App;
src/notify.js
function notify() {
alert('종소리 울려라 종소리 울려~');
}
export default notify;
2. 컴포넌트 스프리팅
src/App.js
import React, { Component } from 'react';
class App extends Component {
state = {
SplitMe: null
};
handleClick = () => {
import('./SplitMe').then(({ default: SplitMe }) => {
this.setState({
SplitMe
});
});
};
render() {
const { SplitMe } = this.state;
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
{SplitMe && <SplitMe />}
</div>
);
}
}
src/notify.js
import React from 'react';
const SplitMe = () => {
return <div>날, 필요할때만 불러.</div>;
};
export default SplitMe;
3. HOC를 이용한 스프리팅
src/App.js
import React, { Component } from 'react';
import withSplitting from './withSplitting';
const SplitMe = withSplitting(() => import('./SplitMe'));
class App extends Component {
state = {
visible: false
};
handleClick = () => {
this.setState({
visible: true
});
};
render() {
const { visible } = this.state;
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
{visible && <SplitMe />}
</div>
);
}
}
export default App;
src/withSplitting.js
import React, { Component } from 'react';
const withSplitting = getComponent => {
// 여기서 getComponent 는 () => import('./SplitMe') 의 형태로 함수가 전달되야합니다.
class WithSplitting extends Component {
state = {
Splitted: null
};
constructor(props) {
super(props);
getComponent().then(({ default: Splitted }) => {
this.setState({
Splitted
});
});
}
render() {
const { Splitted } = this.state;
if (!Splitted) {
return null;
}
return <Splitted {...this.props} />;
}
}
return WithSplitting;
};
export default withSplitting;
'React' 카테고리의 다른 글
Component LifeCycle API (0) | 2019.07.02 |
---|---|
01. React 시작하기 (Mac) (0) | 2019.06.30 |