Renders a component with collapsible content.
- Use the 
React.setState()hook to create theisCollapsedstate variable with an initial value ofprops.collapsed. - Use an object, 
style, to hold the styles for individual components and their states. - Use a 
<div>to wrap both the<button>that alters the component’sisCollapsedstate and the content of the component, passed down viaprops.children. - Determine the appearance of the content, based on 
isCollapsedand apply the appropriate CSS rules from thestyleobject. - Finally, update the value of the 
aria-expandedattribute based onisCollapsedto make the component accessible. 
代码实现
function Collapse(props) {
  const [isCollapsed, setIsCollapsed] = React.useState(props.collapsed);
  const style = {
    collapsed: {
      display: 'none'
    },
    expanded: {
      display: 'block'
    },
    buttonStyle: {
      display: 'block',
      width: '100%'
    }
  };
  return (
    <div>
      <button style={style.buttonStyle} onClick={() => setIsCollapsed(!isCollapsed)}>
        {isCollapsed ? 'Show' : 'Hide'} content
      </button>
      <div
        className="collapse-content"
        style={isCollapsed ? style.collapsed : style.expanded}
        aria-expanded={isCollapsed}
      >
        {props.children}
      </div>
    </div>
  );
}
使用样例
ReactDOM.render(
  <Collapse>
    <h1>This is a collapse</h1>
    <p>Hello world!</p>
  </Collapse>,
  document.getElementById('root')
);