【发布时间】:2019-06-28 03:04:19
【问题描述】:
我有一个呈现按钮的数组,当我单击此按钮时,我只需要更改连接到该按钮的该数组的项目,添加连接到该 localStorage 的用户的名称。目前,当我单击按钮时,它正在更改数组中的所有项目。为了提供帮助,我在此链接中给出了我需要的功能示例:https://codesandbox.io/embed/lots-tojln
我需要按钮单独工作
import React from "react";
import "./styles.css";
const separator = "/";
export default class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
toggleButton: true,
lots: [
{
lotNumber: "1",
lotPrice: "10.00",
lotPriceTax: "0.00",
lotType: "U",
lotUniqueNumber: "xZ38Dw7bDwD33z469xcB4yy3b64D3z",
quantity: 2,
ticketName: "Camarote",
ticketPrevenda: "false",
ticketUniqueNumber: "3WaDBCcawdzyZdAZYBCBz1zb170x47",
total: 20,
totalLotPrice: 10
},
{
lotNumber: "1",
lotPrice: "10.00",
lotPriceTax: "0.00",
lotType: "M",
lotUniqueNumber: "xZ38Dw7bDwD33z469xcB4yy3b64D3z",
quantity: 2,
ticketName: "Camarote",
ticketPrevenda: "false",
ticketUniqueNumber: "3WaDBCcawdzyZdAZYBCBz1zb170x47",
total: 20,
totalLotPrice: 10
}
],
userName: ""
};
this.ticketsCheckDocument = this.ticketsCheckDocument.bind(this);
this.ticketChange = this.ticketChange.bind(this);
}
ticketsCheckDocument(e) {
const [ticketUniqueNumber, lotType, Name] = e.target.value.split(separator);
console.log(ticketUniqueNumber);
console.log(lotType);
console.log(Name);
this.setState({ toggleButton: false });
this.setState({ userName: Name });
}
ticketChange() {
this.setState({ toggleButton: true });
this.setState({ userName: "" });
}
render() {
const lots = this.state.lots.map((lot, l) => (
<div className="box-ticket" key={l}>
<div className="box-vertical">
<h4 className="ticket-type">
{lot.lotType === "U"
? "Unissex"
: lot.lotType === "M"
? "Male"
: "Female"}{" "}
<br />
<small>R$ {lot.lotPrice}</small>
</h4>
</div>
<div className="box-text">
<h4 className="ticket-user-name">{this.state.userName}</h4>
<p className="text-center">
The invitations are nominal. <br />
Please indicate below who will use this invitation
</p>
<div className="box-button">
{this.state.toggleButton ? (
<div>
<button
type="button"
className="btn btn-primary"
value={`${lot.ticketUniqueNumber}${separator}${
lot.lotType
}${separator}Teste ${l}`}
onClick={this.ticketsCheckDocument}
>
It's My
</button>
<button type="button" className="btn btn-primary">
I'll Give
</button>
</div>
) : (
<button
type="button"
className="btn btn-primary"
onClick={this.ticketChange}
>
Change
</button>
)}
</div>
</div>
</div>
));
return <div>{lots}</div>;
}
}
【问题讨论】:
-
我会将代码移动到一个组件中,让每个组件管理它的状态。
-
但是这个 Card.js 是一个组件
-
沙盒对我来说很奇怪,你能试试我的解决方案吗?
标签: javascript reactjs