[英]I can't create a new card with react
問題:我想編寫一個在按下按鈕時添加新卡的程序。 我可以連接和更改狀態,但是沒有新卡。 (狀態值恆定是沒有問題的。重要的是形成新卡)。
上面有兩個不同的組件。 當按下按鈕(相同狀態)時,我想要創建一個新卡。 但是我無法編寫代碼。
card.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;
如果您想在每次單擊按鈕時創建一個新卡,則應該創建將所有新卡映射到組件的卡數組。 這樣,您每次點擊都會獲得一張新卡,而不用修改舊卡。
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;
調用clickEvent
方法時,不會向state
添加另一個值,但是會覆蓋現有的值: imgUrl
和fullName
。
您必須創建紙牌數組,並通過return
內部的map
方法顯示它們。
如果第一張卡CardStyle
為空,則可以從狀態cards: []
空數組開始,並且僅在this.state.cards.length > 0
顯示CardStyle
組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.