2017-07-06 26 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' } 

希望这会有所帮助。