简体   繁体   中英

Append New React Component onclick

I am relatively new to React, but familiar with JavaScript. I want to make a really simple app and in JavaScript whenever I want to append a new HTML element I do something like this: document.getElementById("root").innerHTML += "<h1>Title</h1>"; . In React I want to append a new MyComponent component to my page whenver my button is clicked. How can I do this in a similar way to .innerHTML += . Below is what I have so far to give an idea, but it does not work.

index.js:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

App.js:

function my_func() {
  var prop1 = prompt("Input here ");
  var prop2 = "new_id";
  document.getElementById("app-root").innerHTML += <MyComponent p1={ prop1 } p2={ prop2 }/>;
}

function App() {
  return (
      <div id="app-root">
      <Button color="primary" onClick={ my_func }>Add</Button>{' '}
      </div>
  );
}

export default App;

You should implement React State here. List of components that you will add is saved to this.state. Here is my suggestion.

This is App.js

import React, { Component } from 'react';
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      clicked: false,
      mycomponentlist:[]
    };
    this.my_func = this.my_func.bind(this);
  }
  my_func(){
     let {mycomponentlist} = this.state;
     var prop1 = prompt("Input here ");
     var prop2 = "new_id";
     mycomponentlist.push({prop1,prop2});
     this.setState({mycomponentlist,clicked:true});
  } 
  render() {
    const {clicked,mycomponentlist} = this.state;
    return (
      <div id="app-root">
         <button  onClick={this.my_func }>Add</button>
         {clicked&& mycomponentlist.map(mycomponent=> <MyComponent p1={ mycomponent.prop1 } p2={ mycomponent.prop2 }/>)}       
      </div>
    );
  }
}

export default App;

This is MyComponent.js

import React, { Component } from 'react';
class MyComponent extends Component {
    render() {
        const { p1,p2} = this.props;
        return (
            <div >
                //you can use p1,p2 here...
                <p>{p1}</p>
                <p>{p2}</p>
            </div>
        )
    }
}
export default MyComponent;

I am sure this will work. When button first clicked then clicked status becomes true so array of components are shown every render.

Try something like this, might have to modify it a little bit according to your specific requirements.

import React,{useState} from 'react';
const App = ()=> {
    const [items, setItems] = useState([]);
    return(
      Your JSX
      {items.map((item)=> {
         return(
          <li>item</li>
         );
      })
      <button onClick={push into items}
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM