问题: 我想编写一个在按下按钮时添加新卡的程序。我可以连接和更改状态,但是没有新卡。 (状态值不变是没有问题的。重要的是新卡的形成。)
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;
上面有两个不同的组件。当按下按钮(相同状态)时,我想要创建一个新卡。但是我无法编写代码。
答案 0 :(得分:1)
如果您每次单击按钮都想创建一个新卡,则应该创建将所有新卡映射到组件的卡数组。这样,您每次点击都会获得一张新卡片,而不用修改旧卡片。
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;
答案 1 :(得分:1)
在调用clickEvent
方法时,您没有在state
中添加另一个值,但是会覆盖现有的imgUrl
和fullName
。
您必须创建纸牌阵列,并通过map
内的return
方法显示它们。
如果第一张卡暂时为空,则可以从状态为cards: []
的空数组开始,并且仅在CardStyle
时显示this.state.cards.length > 0
组件。