我定义了一个名为 fullText 的状态变量。
fullText 默认值为 false。
当单击全文时,我想反转我的状态值并使文本能够关闭和打开。但是当单击时,表中所有行的文本都会打开,如何使其特定于行?
{
!this.state.fullText ?
<div onClick={() => this.setState({ fullText: !this.state.fullText })}
className="text-primary cursor-pointer font-size-14 mt-2 px-2"
key={props.data?.id}>
Full Text
</div>
:
<>
<div onClick={() => this.setState({ fullText: !this.state.fullText
})}className="text-primary cursor-pointer font-size-14 mt-2 px-2"
key={props.data?.id}>
Short Text
</div>
<span>{ props.data?.caption}</span>
</>
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
似乎问题中的代码示例对于每一行都是重复的,但只有 1 个状态
fullText(CodeSandbox 中的showMore)对于所有这些行都是通用的。因此它们都一起打开或关闭。如果您希望每行都有单独的打开/关闭功能,那么每行需要 1 个这样的状态。一个简单的解决方案可能是将此状态嵌入到每行的数据中:
export default class App extends Component { state = { data: [ { id: 1, description: "aaaaa", showMore: false // Initially closed }, // etc. ] }; render() { return ( {this.state.data.map((e) => ( { /* Read the showMore state of the row, instead of a shared state */ e.showMore === false ? ( this.setState({ data: changeShow(this.state.data, e.id, true) })}>
Show description{" "}
) : (
this.setState({ data: changeShow(this.state.data, e.id, false) })}>
Show less{" "}
{e.description}
>
)}
>
))}
>
);
}
}
/**
* Update the showMore property of the
* row with the given id.
*/
function changeShow(data, id, show) {
for (const row of data) {
if (row.id === id) { // Find the matching row id
row.showMore = show; // Update the property
}
}
return data;
}