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

时间:2019-01-03 12:52:52

标签: reactjs react-component

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

摆脱了无用的: null结果。

答案 2 :(得分:0)

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

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