附加新的 React 组件 onclick

bar*_*kyn 2 html javascript reactjs

我对 React 比较陌生,但熟悉 JavaScript。我想打一个非常简单的应用程序,并在JavaScript中,每当我想追加一个新的HTML元素我做这样的事情: document.getElementById("root").innerHTML += "<h1>Title</h1>";。在 React 中,每当单击我的按钮时,我都想将一个新的 MyComponent 组件附加到我的页面。我怎样才能以类似于.innerHTML +=. 以下是我到目前为止给出的想法,但它不起作用。

索引.js:

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

应用程序.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;
Run Code Online (Sandbox Code Playgroud)

dev*_*nja 6

你应该在这里实现 React State。您将添加的组件列表保存到 this.state。这是我的建议。

这是 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;
Run Code Online (Sandbox Code Playgroud)

这是 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;
Run Code Online (Sandbox Code Playgroud)

我相信这会奏效。当第一次单击按钮然后单击状态变为 true 时,每次渲染都会显示组件数组。