如何将TSX格式的响应式Logo组件转换为JS文件
将TSX Logo组件转换为功能一致的JS文件
要把你的TSX Logo组件转成功能完全一致的JS文件,只需移除所有TypeScript专属的类型声明,保留原有业务逻辑和React语法即可,具体转换后的代码如下:
import React from "react"; import { Link } from "react-router-dom"; import styled from "styled-components"; import { Breakpoints } from "../../GlobalStyle"; import useMediaQuery from "./useMediaQuery"; const StyledImage = styled.img` height: ${({ height }) => (height ? height : "40px")}; width: auto; cursor: pointer; @media (max-width: ${Breakpoints.mobile}px) { height: 28px; } `; const ResponsiveLogo = ({ id, height }) => { const isMobile = useMediaQuery(`(max-width: ${Breakpoints.mobile}px)`); let Url = isMobile ? "image1_link" : "image2_link" ; return ( <> <Link to="/"> <StyledImage id={id} height={height} alt="logo" src={Url} /> </Link> </> ); }; export default ResponsiveLogo;
转换说明:
- 移除了TypeScript的
Props类型定义、FC<Props>组件类型标注,以及styled组件上的<Props>泛型约束 - 组件参数直接通过解构获取,TypeScript的可选参数逻辑在JS中天然支持(
height作为可选属性,不传值时会默认取样式里的 fallback 值) - 所有样式逻辑、媒体查询判断、路由跳转和JSX结构完全保留,功能和原TSX组件完全一致
内容的提问来源于stack exchange,提问作者Miss Shrivastava
相关产品推荐
相关产品推荐

