首页 > 解决方案 > 追加新的 React 组件 onclick

问题描述

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

index.js:

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

应用程序.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;

标签: javascripthtmlreactjs

解决方案


你应该在这里实现 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;

这是 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;

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


推荐阅读