2017-07-06 54 views
1

我目前正在嘗試將React組件集成到遺留Web項目(一個巨大的html索引文件和一些主要使用jquery的js腳本)中。在現有的Web項目中隱藏React組件

我想將呈現的反應組件添加到單獨的選項卡中。現在問題是我無法控制頂級React組件的可見性。

說我有下面的src代碼在HTML:

... 
<div id="wrapper"> 
    <div id="react-component"></div> 
</div> 
... 

我使用陣營呈現該內部部件。現在有沒有辦法控制「#wrapper」或「#react-component」的可見性? jquery沒有幫助。

我對React比較陌生,看起來將它集成到舊項目中可能是一個巨大的痛苦。

+1

'$ .hide()'和'$ .show()'來自jquery沒有幫助嗎? – flocks

+0

可悲的是它不起作用。 $(「#react-component」)。hide()不起作用。 –

+0

@VittVolt您是否嘗試過使用style = {{display:'none'}}爲父div? – Upasana

回答

3

我使用React渲染內部組件。現在有沒有辦法控制「#wrapper」或「#react-component」的可見性?

那麼這些是兩個不同的世界。

對於#wrapper,您可以使用DOM操作,如$.hide()$.show(),或者通常在jQuery中執行此操作。

對於#react-component您需要致電ReactDOM.render(),並且您可以傳入visible prop來更改呈現元素的可見性。例如:

ReactDOM.render(
    <MyComponent visible={isReactComponentVisible} />, 
    document.getElementById("react-component") 
); 

現在您的React組件可以顯示或隱藏自己,無論您想要什麼。

class MyComponent extends React.Component { 
    render() { 
    return (
     <div style={{ display: this.props.visible ? "block" : "none" }}> 
     ... 
     </div> 
    ) 
    } 
} 

當然它您可以隨時隨地調用ReactDOM.render()isReactComponentVisible變化。像Redux這樣的正式的狀態綁定庫可以幫助你,如果複雜性保證的話。

記住陣營將會給出的渲染所以調用ReactDOM.render()重建整個組件的DOM(如jQuery的是),正是改變(即由visible道具實現的DOM:在style.display屬性)

1

創建一個js文件並導出默認函數來幫助渲染反應組件。

像這樣

import React from 'react'; 
import ReactDOM from 'react-dom'; 
export default function(component, container , props = {}, callback){  

    React.createElement(component , props); 
    ReactDOM.render(component, container, callback); 

} 

你的組件將看起來像這樣

import React,{PropTypes} from 'react'; 

class MySampleComponent extends React.Component{ 

    static propTypes ={ 
     hide : PropTypes.bool 
    } 
    static defaultProps= { 
     hide : false 
    } 

    render(){ 
     return(
     <div style={display : this.props.hide : 'none' : 'block'}> </div> 

    ); 



    } 

} 

導入上述功能呈現在js文件的組成部分,你將index.html中添加

import render from './pathto/RenderHelper' 
import MyComponent from './MyComponent' 

class IndexPage { 

    constructor(){ 
    this.renderUI(); 
    } 

    renderUI(){ 
    var container = document.getElementById('react-component'); 
    render(MyComponent, container, {hide : false}); 
    } 
} 

請注意,您需要將您的page.index.js文件添加到webpack.config.js條目,以便webpack ca ñ編譯它,像這樣。

entry: { page.index : 'location/to/page.index.js' } 

希望這會有所幫助。