我试图根据是否存在数据来更改图标的状态。例如,如果“喜欢”计数器大于0,则将填充该圆圈,否则它将是一个空圆圈。
我一直无法弄清楚如何通过useState呈现此图像
import React, { useState } from "react";
import ActivityIconEngaged from "./ActivityIconEngaged";
import { Modal, Button } from "react-bootstrap";
import PropTypes from "prop-types";
import data from "../Assets/ActivityData";
import { faCircle } from "@fortawesome/pro-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
class ActivityIcon extends React.Component {
constructor(props) {
super(props);
this.state = {
activities: data.activities,
activity: data.activities[0]
};
}
render() {
const { activities, activity } = this.state;
return (
<div>
{activities.map(activity => (
<ActivityIconData key={activity._id} activity={activity} />
))}
</div>
);
}
}
function ActivityIconData({ activity }) {
const { index, likeCount } = activity;
const [show, setShow] = useState(false);
const handleClose = () => {
setShow(false);
};
const [trigger, setTrigger] = useState({ showContent: true });
const showContent = trigger;
const openModal = e => {
e.preventDefault();
setShow(true);
};
if ({ likeCount } > 0) {
setTrigger(!trigger);
}
return (
<>
<div id={`activity-${index}`}>
<span onClick={openModal} className="mr-1">
{showContent ? (
<FontAwesomeIcon
icon={faCircle}
size="2x"
className="ActivityIconDefault"
/>
) : (
<ActivityIconEngaged />
)}
</span>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Activity</Modal.Title>
</Modal.Header>
<Modal.Body>likes: {likeCount}</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</div>
</>
);
}
ActivityIconData.propTypes = {
activity: PropTypes.object.isRequired
};
export default ActivityIcon;
我目前得到的结果是,单击圆圈时模态成功打开,但是,当点赞次数超过0时,圆圈未填充。
答案 0 :(得分:0)
乍看之下,您的情况始终为假,因为您在object
和number
之间进行了一次comparison。
对于严格比较或抽象比较,两个不同的对象永远都不相等。
// instead of { likeCount } > 0, which always results false
if (likeCount > 0) {
setTrigger(!trigger);
}
答案 1 :(得分:0)
我认为您声明的状态太多,无法处理此问题。您不需要likeCount
以及带有trigger
属性的showContent
变量。
如果要使用三元运算符显示图标,则可以将showContent
替换为likeCount
的表达式:
{likeCount > 0 ? <FontAwesomeIcon icon={faCircle} size="2x" className="ActivityIconDefault" /> : <ActivityIconEngaged />}