首页 > 解决方案 > 在 React 中单击按钮时需要多次创建卡片组件

问题描述

因此,我想通过单击按钮多次创建卡片组件,但问题是它只创建cardComponent一次。我该怎么办?有没有人可以创建这些。

这是图像

这是代码:

class GCARD extends Component {
  constructor(props) {
    super(props);
    // This state changes so the card is generated
    this.state = {
        change: '',
    }
    this.handel = this.handel.bind(this);
  }

  handel = (element) => {
    // This is the element which creates the card. 
    element = <CardComponent data="Give a little detail about the thing's you like!"
    heading= "Create Your Own Card" image="./owl.jpg"/>
    this.setState({
        change: element
    });
  }

  render() {
    return (
      <div>
        <div className="form-div">
          <div>
            <p className="form-title">Create Your Own Card</p>
            <hr/>
          </div>
          <div>
          <label className="form-label">Main Heading </label>
          <input className="form-input" type="text"/>
          <br/><br/>
          <label className="form-label">Some Info</label>
          <input className="form-input1" type="text"/>
          <br/><br/>
          {/* Just focus on the button */}
          <button onClick={this.handel} className="form-btn">CREATE</button>
        </div>
        </div>
        <div>
          {this.state.change}
        </div>
      </div>
    );
  }
}

标签: javascriptreactjs

解决方案


您当前的代码仅替换该元素。您想改用数组,例如像这样使用它

this.setState({
        change: this.state.change.concat(element)
    });

推荐阅读