首页 > 解决方案 > 我无法通过反应创建新卡

问题描述

问题: 我想编写一个在按下按钮时添加新卡的程序。我可以连接和更改状态,但没有新卡。(状态中的值不变是没有问题的,重要的是新卡的形成)。

上面有两个不同的组件。当按下按钮时(相同状态),我想要创建一张新卡。但我无法编写代码。


卡片.jsx

import React from 'react'
import CardStyle from '../cardStyle/cardStyle';

class Card extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      imageUrl: null,
      fullName: null,
      job: null
    };
  }

  clickEvent = () => {
    this.setState({
      fullName: 'Furkan',
      job: 'Software engineer'
    });
  }

  render() {
    let {isLoading, imageUrl, fullName, job} = this.state;
    return (
      <div>
        <CardStyle 
              isLoading={isLoading}
              imageUrl = {imageUrl}
              fullName = {fullName}
              job = {job}
              clicked = {this.clickEvent}
              />
        <button onClick={this.clickEvent}>ADD PERSON</button>
      </div>
    )
  }
}

export default Card;

cardStyle.jsx

import React, { Component } from 'react'
import classes from "./cardStyle.css";
import Wrap from "../../Wrap/Wrap";

class CardStyle extends Component {
  state = {
    image: null,
    fullName: null,
    job: null
  };

  createCard = () => {
    return(
      <div className={classes.Card}>      
        <div className={classes.Image}>{this.props.imageUrl}</div>
        <div className={classes.Title}>{this.props.fullName}</div>
        <div className={classes.Job}>{this.props.job}</div>
      </div>
    )
  };

  render() {
    return (
      <Wrap>
        {this.createCard()}
      </Wrap>
    ) 
  }
}

export default CardStyle;

标签: javascriptreactjs

解决方案


如果您想在每次单击按钮时创建一张新卡片,您应该创建卡片数组,将每张新卡片映射到一个组件。这样,您每次点击都会获得一张新卡,而不是修改旧卡。

import React from 'react'
import CardStyle from '../cardStyle/cardStyle';

class Card extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      cards: [
        {
          isLoading: true,
          imageUrl: null,
          fullName: null,
          job: null
        }
      ]
    };
  }

  clickEvent = () => {
    const cards = [
      ...this.state.cards,
      {
        fullName: 'Furkan',
        job: 'Software engineer'
      }
    ]; // This will create a new array from the old one with a new additional value
    this.setState({ cards });
  }

  render() {
    const { cards } = this.state;
    return (
      <div>
        {cards.map((card, index) => (
            <CardStyle 
              key={index}
              isLoading={card.isLoading}
              imageUrl = {card.imageUrl}
              fullName = {card.fullName}
              job = {card.job}
              />
        )}

        <button onClick={this.clickEvent}>ADD PERSON</button>
      </div>
    )
  }
}

export default Card;

推荐阅读