ReactJS中条件渲染的正确实现:按需显示链接组件
解决React条件渲染显示链接的问题
我正在学习ReactJS,这个简单的条件渲染问题让我十分困扰。我希望在代码标注的链接区域添加条件判断,仅当传入的link参数存在有效值时才显示该链接。我尝试了两种写法但都未成功,代码如下:
//import { BsGithub } from "react-icons/bs"; //import { FaYoutube } from "react-icons/fa"; import { FaEye } from "react-icons/fa"; interface Props { title: string; des: string; src: string; link: string; } const ProjectsCard = ({ title, des, src, link}: Props) => { return ( <div className="w-full p-4 xl:px-12 h-auto xl:py-10 rounded-lg shadow-shadowOne flex flex-col bg-gradient-to-r from-bodyColor to-[#202327] group hover:bg-gradient-to-b hover:from-gray-900 hover:gray-900 transition-colors duration-1000"> <div className="w-full h-[80%] overflow-hidden rounded-lg"> <img className="w-full h-60 object-cover group-hover:scale-110 duration-300 cursor-pointer" src={src} alt="src" /> </div> <div className="w-full mt-5 flex flex-col gap-6"> <div> <div className="flex items-center justify-between"> <h3 className="text-base uppercase text-designColor font-bold"> {title} </h3> <div className="flex gap-2"> // Need if Statement here ... show link only if 'link' parameter has a value // Guess I can't do if {link.length} > 0 { <a href={link} target="_blank"> <span className="text-lg w-10 h-10 rounded-full bg-black inline-flex justify-center items-center text-gray-400 hover:text-designColor duration-300 cursor-pointer"> <FaEye /> </span> </a> // end if statement here </div> </div> <p className="text-sm tracking-wide mt-3 hover:text-gray-100 duration-300"> {des} </p> </div> </div> </div> ); }; export default ProjectsCard;
我尝试过的错误写法
if {link.length} > 0 {}:JSX中不能直接使用普通if语句,必须用大括号包裹表达式语法- 三元表达式
{link} ? ::语法不完整,缺少条件为真和假时的返回内容
正确的两种实现方式
方法1:使用逻辑与运算符(&&)
JSX中,逻辑与运算符会在左侧条件为真时渲染右侧元素,条件为假时返回null(不渲染内容)。修改代码如下:
<div className="flex gap-2"> {/* 仅当link存在且长度大于0时渲染链接 */} {link && link.length > 0 && ( <a href={link} target="_blank" rel="noopener noreferrer"> <span className="text-lg w-10 h-10 rounded-full bg-black inline-flex justify-center items-center text-gray-400 hover:text-designColor duration-300 cursor-pointer"> <FaEye /> </span> </a> )} </div>
方法2:使用完整的三元表达式
三元表达式需要明确写出条件为真和假时的返回值,假时返回null即可:
<div className="flex gap-2"> {/* 三元表达式实现条件渲染 */} {link && link.length > 0 ? ( <a href={link} target="_blank" rel="noopener noreferrer"> <span className="text-lg w-10 h-10 rounded-full bg-black inline-flex justify-center items-center text-gray-400 hover:text-designColor duration-300 cursor-pointer"> <FaEye /> </span> </a> ) : null} </div>
补充说明
- 建议给
<a>标签添加rel="noopener noreferrer"属性,避免安全风险 - 如果
link可能是undefined或null,需先判断link是否存在,再校验长度
内容的提问来源于stack exchange,提问作者timroman
相关产品推荐
相关产品推荐

