여러 페이지 앱에서 React 사용
나는 React와 놀고 있었고 지금까지는 정말 좋아합니다. NodeJS로 앱을 구축 중이며 애플리케이션 전체의 일부 대화식 구성 요소에 React를 사용하고 싶습니다. 단일 페이지 앱으로 만들고 싶지 않습니다.
웹에서 다음 질문에 대한 답변을 찾지 못했습니다.
여러 페이지 앱에서 React 컴포넌트를 분리하거나 묶는 방법은 무엇입니까?
앱의 일부 섹션에서 절대로드 할 수는 없지만 현재 모든 구성 요소가 하나의 파일에 있습니다.
지금까지 React가 렌더링 할 컨테이너의 ID를 검색하여 구성 요소를 렌더링하기 위해 조건문을 사용하려고합니다. React의 모범 사례가 무엇인지 100 % 확신하지 못합니다. 이런 식입니다.
if(document.getElementById('a-compenent-in-page-1')) {
React.render(
<AnimalBox url="/api/birds" />,
document.getElementById('a-compenent-in-page-1')
);
}
if(document.getElementById('a-compenent-in-page-2')) {
React.render(
<AnimalBox url="/api/cats" />,
document.getElementById('a-compenent-in-page-2')
);
}
if(document.getElementById('a-compenent-in-page-3')) {
React.render(
<AnimalSearchBox url="/api/search/:term" />,
document.getElementById('a-compenent-in-page-3')
);
}
아직 설명서를 읽고 있는데 아직 다중 페이지 앱에 필요한 것을 찾지 못했습니다.
미리 감사드립니다.
현재 비슷한 것을하고 있습니다.
응용 프로그램은 완전한 React 앱이 아닙니다 .Autark 인 CommentBox와 같은 동적 항목에 React를 사용하고 있습니다. 그리고 특별한 매개 변수가있는 모든 지점에 포함될 수 있습니다 ..
그러나 모든 하위 앱이로드되어 단일 파일 all.js
에 포함되므로 브라우저에서 여러 페이지에 걸쳐 캐시 할 수 있습니다.
SSR 템플릿에 앱을 포함시켜야하는 경우 클래스 "__react-root"와 특수 ID (렌더링 할 React 앱의 이름)가 포함 된 DIV 만 포함하면됩니다.
논리는 정말 간단합니다.
import CommentBox from './apps/CommentBox';
import OtherApp from './apps/OtherApp';
const APPS = {
CommentBox,
OtherApp
};
function renderAppInElement(el) {
var App = APPS[el.id];
if (!App) return;
// get props from elements data attribute, like the post_id
const props = Object.assign({}, el.dataset);
ReactDOM.render(<App {...props} />, el);
}
document
.querySelectorAll('.__react-root')
.forEach(renderAppInElement)
<div>Some Article</div>
<div id="CommentBox" data-post_id="10" class="__react-root"></div>
<script src="/all.js"></script>
편집하다
webpack은 코드 분할 및 LazyLoading을 완벽하게 지원하므로 모든 앱을 하나의 번들로로드 할 필요는 없지만 분할하여 요청시로드하는 예제를 포함하는 것이 좋습니다.
import React from 'react';
import ReactDOM from 'react-dom';
const apps = {
'One': () => import('./One'),
'Two': () => import('./Two'),
}
const renderAppInElement = (el) => {
if (apps[el.id]) {
apps[el.id]().then((App) => {
ReactDOM.render(<App {...el.dataset} />, el);
});
}
}
You can provide several entry points for the application in the webpack.config.js file:
var config = {
entry: {
home: path.resolve(__dirname, './src/main'),
page1: path.resolve(__dirname, './src/page1'),
page2: path.resolve(__dirname, './src/page2'),
vendors: ['react']
},
output: {
path: path.join(__dirname, 'js'),
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js'
},
}
then you can have in your src folder three different html files with their respective js files (example for page1):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page 1</title>
</head>
<body>
<div id="app"></div>
<script src="./vendors.js"></script>
<script src="./page1.bundle.js"></script>
</body>
</html>
JavaScript file:
import React from 'react'
import ReactDom from 'react-dom'
import App from './components/App'
import ComponentA from './components/ReactComponentA'
ReactDom.render(<div>
<App title='page1' />
<ReactComponentA/>
</div>, document.getElementById('app'))
Different React components can be then loaded for each single page.
Edit: 11/01/2015
I'm building an application from the ground up and am learning as I go, but I think what you are looking for is React-Router. React-Router maps your components to specific URLs. For example:
render((
<Router>
<Route path="/" component={App}>
<Route path="api/animals" component={Animals}>
<Route path="birds" component={Birds}/>
<Route path="cats" component={Cats}/>
</Route>
</Route>
<Route path="api/search:term" component={AnimalSearchBox}>
</Router>
), document.body)
In the search case, 'term' is accessible as a property in the AnimalSearchBox:
componentDidMount() {
// from the path `/api/search/:term`
const term = this.props.params.term
}
Try it out. This tutorial is the one that put me over the top in terms of my understanding of this and other related topics.
Original answer follows:
I found my way here looking for the same answer. See if this post inspires you. If your application is anything like mine, it will have areas that change very little and varies only in the main body. You could create a widget whose responsibility it is to render a different widget based upon the state of the application. Using a flux architecture, you could dispatch a navigation action that changes the state your body widget switches upon, effectively updating the body of the page only.
That's the approach I'm attempting now.
Are you using a CMS? They tend to like changing urls which could break your application.
Another way is using something like React Habitat.
With it, you can register components and they automatically get exposed to the dom.
Example
Register component(s):
container.register('AnimalBox', AnimalBox);
container.register('AnimalSearchBox', AnimalSearchBox);
Then they are availiable in your dom like this:
<div data-component="AnimalBox"></div>
<div data-component="AnimalSearchBox"></div>
The above will be automatically replaced with your react components.
You can then automatically pass properties (or props) to your components too:
<div data-component="AnimalBox" data-prop-size="small"></div>
This will expose size
as a prop to your component. There are additional options for passing other types such as json, array's, ints, floats etc.
I know it's been a while since this question was asked but hopefully this helps someone.
As @Cocomico mentioned you could provide several entry points for the application in the webpack.config.js file. If you are looking for a simple Webpack setup (based on the idea of multiple entry points) that allows you to add React components to static pages you may consider using this: https://github.com/przemek-nowicki/multi-page-app-with-react
참고URL : https://stackoverflow.com/questions/31933359/using-react-in-a-multi-page-app
'IT story' 카테고리의 다른 글
ASP.Net 양식에 제출 된 게시물 데이터 읽기 (0) | 2020.08.06 |
---|---|
react.js의 인스턴스 v 상태 변수 (0) | 2020.08.06 |
mysql에서 같은 테이블에서 어떻게 두 번 조인합니까? (0) | 2020.08.06 |
PostgreSQL-기존 권한으로 사용자를 빠르게 삭제하는 방법 (0) | 2020.08.06 |
jquery 특정 인덱스에서 테이블에 새 행 삽입 (0) | 2020.08.06 |