基于布尔值React的HTML元素的条件呈现



构建一个组件,该组件采用一个值(attribute.readonly(,并且只显示前40个字符,除非触发了<Chevron onClick,这意味着我希望显示fullDescription而不是shortHeading-理想情况下,这将类似于它目前只将Accordion的高度增加一倍的方式,以允许容纳其余内容。我知道我还有点落后,但如果能为我的下一步行动/改进我已经拥有的东西提供一些建议,我将不胜感激!

// @flow
import styled from "styled-components";
import chevron from "../Assets/chevron-icon.svg";
type Props = { attribute: AttributeType, className?: string };
const Accordion = styled.div`
background-color: #e5e9eb;
height: 56px;
width: 612px;
border-radius: 2px;
border: 1px solid #27282a;
margin-bottom: 48px;
display: flex;
align-items: center;
span {
padding-left: 24px;
}
`;
const Chevron = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
`;
const ExpandableString = ({ attribute, className }: Props) => {
const fullDescription = attribute.readonlyvalue;
const shortHeading = fullDescription.substring(0, 40) + '...';
const isExpanded = false;
function toggleContent() {
isExpanded = true;
}
return (
<Accordion className={className}> 
<span>{shortHeading}</span>
<Chevron onClick={toggleContent} src={chevron} alt="Expand or collapse content" />
</Accordion>
);
};
export default ExpandableString;

将数据置于状态并将其切换为

const ExpandableString = ({ attribute, className }: Props) => {
const [isExpanded, setIsExpanded] = React.useState(false);
function toggleContent() {
setIsExpanded(prev => !prev);
}
return (
<Accordion className={className}> 
<span>{shortHeading}</span>
<Chevron onClick={toggleContent} src={chevron} alt="Expand or collapse content" />
</Accordion>
);
};

然后,根据isExpanded状态,可以有条件地渲染React组件。

最新更新