展开单个映射项的略图文本



在我的react应用程序中,我返回的数据包含不同长度的文本。

const ReturnedProducts = () => {
const textStyle = {
maxWidth: '100%',
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
marginBottom: '10px',
};
//This function returns the correct style to the above div.
function calculateTextStyle() {
return truncate ? textStyle : null;
}
// Manage if the text should be truncated or not.
const [truncate, setToggleTruncate] = React.useState(true);
// Function to toggles the state variable 'truncate', thereby expanding and truncating the text when the user clicks the div.
function toggleTruncate() {
setToggleTruncate(!truncate);
}
return (
<div>
<AreaWrapper>
<InnerWrapper>
{data.data.products &&
products.map(product => (
<ProjectCard key={product.id}>
<img src={product.image} alt="test" />
<ProjectCardTitle
onClick={toggleTruncate}
style={calculateTextStyle()}
>
{product.title}
</ProjectCardTitle>
<ProjectButton>
{product.description}
</ProjectButton>
</ProjectCard>
))}
</InnerWrapper>
</AreaWrapper>
</div>
);
};
export default withRouter(ReturnedProducts);

展开功能很好,但是,当我单击页面上的一张卡片时,文本会展开所有卡片。我怎样才能使它只展开点击的卡片?提前谢谢。

因为您将truncate设置为true/false。u应该将其设置为product.id

function toggleTruncate(value) {
setToggleTruncate(value);
}

修改您的组件以使用product.id而不是

<ProjectCardTitle
onClick={() => toggleTruncate(product.id)}
style={ truncate === product.id ? textStyle : null }
>

最新更新