[英]How to only render an individual component with state, when multiple components use that state in React?
I'm currently using state to display/hide an icon in my SwipeRow
, but when I swipe one row, the icon becomes visible on all the rows, because the icons all reference that same state, so my question was how do I display the icon only on the row swiped?我目前正在使用 state 在我的
SwipeRow
中显示/隐藏一个图标,但是当我滑动一行时,该图标在所有行上都可见,因为这些图标都引用了相同的 state,所以我的问题是如何显示图标仅在刷过的行上?
I was thinking maybe I can utilize index
somehow in .map()
, like wrap StyledContainer
with a ternary using index
, I'm not sure.我在想也许我可以在
.map()
中以某种方式利用index
,比如使用index
将StyledContainer
包装成三元组,我不确定。 Any ideas on how to achieve this?关于如何实现这一目标的任何想法? If you have a method without using state, that's also fine.
如果您有不使用 state 的方法,那也没关系。
const foobar = content.map((object, index) => {
return (
<SwipeRow
onRowOpen={() => setSwiped(true)}
onRowClose={() => setSwiped(false)}
>
<StyledContainer swiped={isSwiped}> <-- This is where it's displayed/hidden
<Icon />
</StyledContainer>
</SwipeRow>
)})
You will have to maintain a state for all Swipe rows.您必须为所有 Swipe 行维护 state。 Maybe a map or an object.
也许是 map 或 object。 Something like this.
像这样的东西。
const [swiped, setSwiped] = React.useState({});
const content = content.map((object, index) => {
const id = object.id;
return (
<SwipeRow
onRowOpen={() => setSwiped((oldSwipe) => { oldSwipe.id = true; return oldSwipe;})}
onRowClose={() => setSwiped((oldSwipe) => { oldSwipe.id = false; return oldSwipe;})}
>
<StyledContainer swiped={swiped[id]}> <----- This is where it's displayed/hidden
<Icon />
</StyledContainer>
</SwipeRow>
)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.