React.js: How to append a component on click?

后端 未结 2 919
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 07:06

I\'m new to React and I\'m puzzled on something kind of basic.

I need to append a component to the DOM after the DOM is rendered, on a click event.

My initia

2条回答
  •  死守一世寂寞
    2020-12-04 07:30

    Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

    What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

    class AppComponent extends React.Component {
      state = {
        numChildren: 0
      }
    
      render () {
        const children = [];
    
        for (var i = 0; i < this.state.numChildren; i += 1) {
          children.push();
        };
    
        return (
          
            {children}
          
        );
      }
    
      onAddChild = () => {
        this.setState({
          numChildren: this.state.numChildren + 1
        });
      }
    }
    
    const ParentComponent = props => (
      

    Add Another Child Component

    {props.children}
    ); const ChildComponent = props =>
    {"I am child " + props.number}
    ;

提交回复
热议问题