基于布尔值 React 的 HTML 元素条件渲染

时间:2021-05-13 09:29:50

标签: html css reactjs onclick styled-components

构建一个接受值 (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;

1 个答案:

答案 0 :(得分:0)

将您的数据放入状态并切换它

QOS 1

然后,根据 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> ); }; 状态,您可以有条件地渲染您的 React 组件。