我已经解决了这个问题,你可以在这里参考工作代码 - https://codesandbox.io/s/focused-tereshkova-f95jj?file=/src/App.js
import "./styles.css";
import React, { useState, useEffect } from "react";
import TestimonialsSettingsUnit from "./TestimonialsSettingsUnit.js";
const data = [
{
name: "Test1",
id: 1,
otherData: "This is a testimonial about Test1",
show: true
},
{
name: "Test2",
id: 2,
otherData: "This is a testimonial about Test2",
show: true
},
{
name: "Test3",
id: 3,
otherData: "This is a testimonial about Test3",
show: false
}
];
const App = () => {
const [selectedTestimonials, setSelectedTestimonials] = useState([]);
const [testimonials, setTestimonials] = useState(data);
useEffect(() => {
const selectedTestimonials = testimonials
.filter(({ show }) => show)
.map(({ id }) => id);
setSelectedTestimonials(selectedTestimonials);
}, [testimonials]);
const handleCheckboxChange = (testimonialId, show) => {
const updatedTestimonials = testimonials.map((testimonial) => {
if (testimonial.id === testimonialId) {
return {
...testimonial,
show
};
}
return testimonial;
});
setTestimonials(updatedTestimonials);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{data.map((testimonial, i) => {
const isSelected = selectedTestimonials.includes(testimonial.id);
const isDisabled = !isSelected && selectedTestimonials.length === 2;
return (
<TestimonialsSettingsUnit
key={testimonial.id}
index={i}
data={testimonial}
handleCheckboxChange={handleCheckboxChange}
isSelected={isSelected}
isDisabled={isDisabled}
/>
);
})}
</div>
);
};
export default App;
import React from "react";
export default function TestimonialsSettingsUnit({
data,
index,
handleCheckboxChange,
isSelected,
isDisabled
}) {
const handleCheck = (event) => {
const { target: { checked } } = event
handleCheckboxChange(data.id, checked)
};
return (
<div className="settings-testimonials-container">
<h4>Testimonial {index + 1}</h4>
<div className="settings-testimonial-controls">
<img
className="settings-profile-img"
src={data.authorPhoto}
alt="User"
/>
<div className="settings-testimonial-info">
<div>
<p>Name</p>
<h5>{data.authorName}</h5>
</div>
<div>
<p>Company</p>
<h5>{data.authorCompany}</h5>
</div>
<div>
<p>Position</p>
<h5>{data.authorTitle}</h5>
</div>
</div>
<div className="settings-testimonial-buttons">
<button>Delete</button>
<br />
<input
id="show"
type="checkbox"
name={`testimonial-${index + 1}`}
checked={isSelected}
onChange={handleCheck}
disabled={isDisabled}
/>
<label htmlFor="show">Show on profile</label>
</div>
</div>
<p>Text</p>
<p>{data.text}</p>
<hr style={{ border: "solid 1px purple" }} />
</div>
);
}