javascript - 我无法通过反应创建新卡
问题描述
问题: 我想编写一个在按下按钮时添加新卡的程序。我可以连接和更改状态,但没有新卡。(状态中的值不变是没有问题的,重要的是新卡的形成)。
上面有两个不同的组件。当按下按钮时(相同状态),我想要创建一张新卡。但我无法编写代码。
卡片.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;
推荐阅读
- algorithm - 我如何判断两张照片是否相同但有一些亮度差异
- c# - 如何在单声道构建脚本中使用 NuGet 包 (grpc)
- php - WooCommerce 根据产品类别更改订单号
- ansible - Ansible:连接角色的最佳实践(meta、rolename: 或 import_role)
- r - 我想在现有变量的帮助下创建新变量
- ios - IOS(苹果)支持的播放器
- c++ - 类中的变量具有错误的值
- text-to-speech - 有没有办法使用
SSML 中的标记以调整单个单词而无需暂停(不使用后处理器) - google-sheets - 更改单元格中的一个值时,自动填写其他单元格
- java - 在 Spring 中使用 RestTemplate 作为请求参数的 MultipartFile + String