2016-11-20 2 views
0

클라이언트 쪽 렌더링과 비교하여 사용자 상호 작용이 거의없는 응용 프로그램에 서버 쪽 렌더링을 사용하는 것이 더 좋으며 서버 쪽 코드를 컴파일하는 데 webpack을 사용하는 것이 좋습니다.서버 쪽 렌더링에 대한 전역 범위 이벤트 처리기 정의 방법

구성 요소가 렌더링 된 후에 테이블 여백 위쪽을 업데이트하려는 시나리오가 있습니다. 이 클라이언트 측 렌더링 경우

componentDidMount() { 
    const node = ReactDOM.findDOMNode(this.refs.table); 
    node.style.marginTop = `-${height}`; 
} 

그러나 다음과 같이 구현은 구성 요소가 렌더링 될 때 호출되지 않습니다 componentDidMount, SSR에 표시됩니다. 그래서 나는 componentWillMount에이 코드를 넣어 및 업데이트 소스 코드

document.addEventListener("DOMContentLoaded", function(event) { const node = document.getElementById('table'); node.style.marginTop = `-${height}`; }); 

다음은 다른 문제를 가지고 다음과 같이.

document is not defined on server 

그 이유는 코드가 노드 환경에서 실행되고 있기 때문입니다. 브라우저 환경과 같이 등이없는 문서가 없습니다. 내가 생각할 수있는 방법은 서버 측에 React 구성 요소를 html 문자열로 렌더링하는 데 사용되는renderPage 함수에 코드를 넣는 것입니다. Server Rendering. 그러나 이벤트 처리기를 최상위 컨텍스트에 배치하면 렌더링 된 다른 페이지가 오염됩니다.

router.get('*', ctx => { 
    match({ routes: routes, location: ctx.url }, (err, redirect, props) => { 
    if (err) { 
     ctx.throw(err.message, 500); 
    } else if (redirect) { 
     ctx.redirect(redirect.pathname + redirect.search) 
    } else if (props) { 
     const appHtml = renderToString(<RouterContext {...props}/>); 
     ctx.body = renderPage(appHtml); 
    } else { 
     ctx.throw(404, 'not fount'); 
    } 
    }) 
}) 
function renderPage(appHtml) { 
    return ` 
    <!doctype html public="storage"> 
    <html> 
    <meta charset=utf-8/> 
    <title>My First React Router App</title> 
    <div id=app>${appHtml}</div> 
    <script type='text/javascript'> 
     document.addEventListener("DOMContentLoaded", function(event) { 
     const node = document.getElementById('table'); 
     node.style.marginTop = `-${height}`; 
     }); 
    </script> 
    ` 
} 

나는 또한 다른 해결책을 찾았습니다. A React component for binding events on the global scope.. 나는 그 최고의 해상도라고 생각하지 않는다.

는 그래서 일반적으로 componentDidMount 또는 클라이언트 측 렌더링과 같은 componentDidUpdate에 넣어 DOM 노드를 조작 할 수있는 더 좋은 방법이 물어보고 싶은.

답변

0

당신이 쓸모없는 것처럼 DOM 노드를 조작하십시오. 귀하의 DOM 컨트롤을 제어 할 수 있습니다. 다음 번에 앱을 다시 렌더링 한 후에 설정된 여백은 React에 의해 무시됩니다.

태클하고 싶은 스타일을 조작하려면 인라인 스타일을 사용하는 것이 좋습니다.

render() { 
    const divStyle={'marginTop': '100px'} 

    return <div style={divStyle}></div> 
} 

또한 UI 기능을 렌더링 기능으로 처리하도록합니다.

리얼 라이프 사이클에서 marginTop을 재설정해야하지만 렌더 기능에서 직접 재설정해야하는 이유가 있습니까?