当然,这很简单,但是我看不到哪里出了问题。
我正在尝试将className
onClick
添加到data.map
的列表中,请注意onClick
我只希望单击的selectedId
添加className
这是我在的地方
class Grid extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
selectedId: null,
};
}
handleClick = selectedId => {
this.setState({
selectedId,
});
};
render() {
const childElements = this.props.amenitiesData.edges.map(
({ node: amenity }) => {
const isActive = amenity.id === this.state.selectedId;
const showCopy = isActive ? 'showCopy' : '';
return (
<div key={amenity.id} className="grid-item">
<div className={`copy-wrapper ${showCopy}`}>
<div className="expand-button">
<a
href="#"
onClick={() => this.handleClick(amenity.id)}
>
...
</a>
</div>
</div>
</div>
);
}
);
return (
<Wrapper>
{childElements}
</Wrapper>
);
}
}
问题是,当我单击任何给定项目时,未添加className
中的showCopy
。
这是amenity.id
的当前数据结构。从parent
传递为const amenitiesData = data.allContentfulAmenities;
请注意,列表中每个项目的数据都是正确的,错误为零。
{
"data": {
"allContentfulAmenities": {
"edges": [
{
"node": {
"id": "8e9e933d-0395-5867-9e30-1c46726766f2"
}
},
{
"node": {
"id": "4e04401c-5bdd-5174-8a2c-ea1fc36c0cc4"
}
},
{
"node": {
"id": "ce89e346-8136-5afa-966b-6eb7443d9272"
}
},
{
"node": {
"id": "7a85ee22-6ec5-5a53-9e60-44012ad24130"
}
},
{
"node": {
"id": "f56e28bb-e1ff-5b59-be3a-1fde9333c79d"
}
},
{
"node": {
"id": "078753ed-e6b0-5770-9ba5-6cb025c3aa5a"
}
},
{
"node": {
"id": "a48ad8df-d084-550b-91e9-e4804308c336"
}
}
]
}
}
}
答案 0 :(得分:2)
在渲染器中执行此操作。
render() {
const childElements = this.props.amenitiesData.edges.map(({ node: amenity }) => {
return (
<div key={amenity.id} className="grid-item">
<div className={`
copy-wrapper
${amenity.id === this.state.selectedIdshowCopy ? showCopy' : ''}
`}>
<div className="expand-button">
<a
href="#"
onClick={() => this.handleClick(amenity.id)}
>
...
</a>
</div>
</div>
</div>
);
}
);
以前的问题是,一旦您的selectedId与amenity.id
匹配,便将selectedIdshowCopy
切换为true
,最终添加了'showCopy to every item in your
。map()`< / p>
答案 1 :(得分:-1)
您需要用div(或按钮)替换<a>
标记,然后绑定onClick
侦听器。当前,您的锚标记具有href,它正在刷新页面,并且组件状态丢失
这是您的代码的有效示例。 https://codesandbox.io/s/zqww1n3r6l
您可以通过检查元素查看反映的变化。