【问题标题】:simplest approach of dynamically adding components in react在反应中动态添加组件的最简单方法
【发布时间】:2019-01-03 12:52:52
【问题描述】:

目前正在研究反应。我有两个组件,比如说 ad 和 home 。在家庭组件内部,我有一个图像,并且在该图像的单击事件中,我想在图像下方的家庭组件内呈现广告。有没有简单的方法。谢谢!

【问题讨论】:

  • 在 Home 组件中保持 isOpen 状态。单击图像时切换它并根据此状态有条件地渲染 AD

标签: reactjs react-component


【解决方案1】:

检查一下。我想这就是你想要的

//dynamically generate div 
let DynamicDiv=()=>{
    return (<div>
        <p>i am here</p>
    </div>)
}

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      visible:false //visibility of Component
    }

    this.divVisiblity=this.divVisiblity.bind(this) //function is bind when user clicks on pic
  }
  divVisiblity(){
    //this function will get called when user clicks on function
    this.setState(()=>{return {visible:!this.state.visible}}) //changes visible state of Component when user clicks

  }
  render() {
    return (
      <div>
      <div className="App">
      {/* onClick is assigned function named divVisiblity */}
        <img onClick={this.divVisiblity} src="https://placekitten.com/g/200/300" alt="test"/>
          {/*this is ternary if else statement in js */}
      {/* if visible = true ,display Component else dont  */}
      <div> 
        {this.state.visible && <DynamicDiv/>}
      </div>
    );
  }
}

【讨论】:

    【解决方案2】:
    I think that will help to you.
    
    export default class HomeComponent extends Component<Props> {
        constructor(props) {
            super(props);
            this.state = {
                renderAdComponent: false
            };
            this.onClickHandler = this.onClickHandler.bind(this);
        }
    
        onClickHandler() {
            this.setState({renderAdComponent: !this.state.renderAdComponent})
        }
    
        render() {
            return (
                <View>
                    <Image onClick={this.onClickHandler}/>
                    {this.state.renderAdComponent ? <AdComponent/> : null}
                </View>
            );
        }
    }
    

    【讨论】:

      【解决方案3】:

      @sdkcy 的建议是可以的,但实际上并不需要三元运算符。您可以执行以下操作

      { this.state.isAdShown &amp;&amp; &lt;ComponentToShow /&gt; }

      这消除了无用的: null 结果。

      【讨论】:

        猜你喜欢
        • 2017-12-14
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        • 2020-02-20
        • 2021-03-05
        • 1970-01-01
        相关资源
        最近更新 更多