【问题标题】:Hide a React component in existing web project在现有 Web 项目中隐藏 React 组件
【发布时间】:2017-12-10 17:11:11
【问题描述】:

我目前正在尝试将 React 组件集成到遗留 Web 项目中(一个巨大的 html 索引文件和一些主要使用 jquery 的 js 脚本)。

我正在尝试将渲染的反应组件添加到单独的选项卡中。现在的问题是我无法控制顶级 React 组件的可见性。

假设我在 html 中有以下 src 代码:

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

我使用 React 渲染内部组件。现在有什么方法可以控制 "#wrapper" 或 "#react-component" 的可见性吗? jquery 没有帮助。

我对 React 比较陌生,似乎将它集成到旧项目中可能会很痛苦。

【问题讨论】:

  • $.hide() 和来自 jquery 的 $.show() 没有帮助?
  • 很遗憾它不起作用。 $("#react-component").hide() 不起作用。
  • @VittVolt 您是否尝试过使用 style={{display: 'none'}} 作为父 div?
  • @Upasana 我在css文件中明确设置了,它也不起作用。

标签: javascript jquery html reactjs


【解决方案1】:

我使用 React 渲染内部组件。现在有什么方法可以控制 "#wrapper" 或 "#react-component" 的可见性吗?

嗯,这是两个不同的世界。

对于#wrapper,您可以只使用像$.hide()$.show() 这样的DOM 操作,或者您通常会在jQuery 中进行操作。

对于#react-component,您需要调用ReactDOM.render(),并且可以传入visible 属性来更改渲染元素的可见性。比如:

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>
    )
  }
}

当然,当isReactComponentVisible 发生变化时,您可以随时致电ReactDOM.render()。如果复杂性需要,像Redux 这样的正式状态绑定库可以在这里为您提供帮助。

请记住,React 将区分渲染,因此调用 ReactDOM.render()不是重建整个组件的 DOM(就像 jQuery 那样),只是改变了什么(即由 visible 属性影响的 DOM :style.display 属性。)

【讨论】:

    【解决方案2】:

    创建一个js文件并导出一个默认函数来帮助你渲染react组件。

    这样

    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 可以编译它,就像这样。

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2019-07-27
      • 1970-01-01
      • 2021-05-22
      • 2020-06-09
      • 2021-06-03
      • 1970-01-01
      • 2017-03-24
      • 2020-09-23
      相关资源
      最近更新 更多