在反应中动态添加组件的最简单方法

simplest approach of dynamically adding components in react

目前正在研究 React。我有两个组件可以说 ad 和 home 。在家庭组件内部我有一张图片,点击该图像的事件我想在图像下方的家庭组件内呈现广告。有没有简单的方法。谢谢!

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

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

{ this.state.isAdShown && <ComponentToShow /> }

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

检查这个。我想这就是你想要的

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