将TypeScript组件Props转为JavaScript及JSX传参方法指导
TypeScript React Skill组件转JavaScript及Props传递方案
1. 转换后的JavaScript组件代码
去掉了TypeScript的类型定义,给可选Props directionLeft 设置默认值 false,还原原组件的可选参数行为:
import React from "react"; import { motion } from "framer-motion"; import image from "../public/img/me.jpg"; import Image from "next/image"; function Skill({ directionLeft = false }) { return ( <div className="group relative flex cursor-pointer"> <motion.div initial={{ x: directionLeft ? -200 : 200, opacity: 0, }} transition={{ duration: 1 }} whileInView={{ opacity: 1, x: 0, }} > <Image src={image} className="rounded-full border"/> </motion.div> </div> ); } export default Skill;
2. 父组件中传递directionLeft Props的示例
在JSX中直接通过属性传递即可,可选参数可以选择不传,此时会使用组件中设置的默认值:
import Skill from './Skill'; function ParentComponent() { return ( <div> {/* 显式传递directionLeft为true */} <Skill directionLeft={true} /> {/* 不传递该Props,使用默认值false */} <Skill /> </div> ); }
内容的提问来源于stack exchange,提问作者Nuwan Chamikara
相关产品推荐
相关产品推荐

