You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React+Tailwind CSS项目中实现餐厅卡片组件内文本的自动换行?

如何在React+Tailwind CSS项目中实现餐厅卡片组件内文本的自动换行?

嘿,我看了你的代码和问题,其实不用复杂的React逻辑,靠Tailwind的内置样式类就能轻松搞定文本换行的问题~ 下面是具体的修改方案:

1. 处理餐厅名称

你现在给餐厅名称的<h3>加了truncate类,这个是强制单行截断的效果。如果想让名称自动换行,直接去掉truncate,换成text-wrap(Tailwind 3.3+版本支持,语义更清晰)或者whitespace-normal:

<h3 className="font-bold text-lg text-wrap">{name}</h3>

要是你想限制名称最多显示2行,超过的部分用省略号截断,可以用line-clamp-2:

<h3 className="font-bold text-lg line-clamp-2">{name}</h3>

2. 处理菜系文本

菜系列表拼接后可能会很长,给对应的<h4>加上text-wrap或者break-words类,就能让文本在卡片的固定宽度(w-[300px])内自动换行:

<h4 className="text-wrap">{cuisines.join(", ")}</h4>

如果遇到特别长的菜系名称,break-words还能拆分长单词,避免超出卡片宽度:

<h4 className="break-words">{cuisines.join(", ")}</h4>

3. 其他文本(评分、人均)

评分和人均消费的内容一般比较短,默认就会正常换行,但如果担心极端情况,也可以给对应的<h4>加上text-wrap类,确保兼容性。

修改后的完整RestaurantCard组件

import { CDN_URL } from "../utils/constants";

const styleCard = {
    backgroundColor: "#f0f0f0"
};

const RestaurantCard =(props) =>{
    const {resData} = props;
    const {cloudinaryImageId,name,cuisines,avgRating,costForTwo} = resData?.info;
    return(
       <div className="m-4 p-4 w-[300px] rounded-lg" style={styleCard}>
          <img className="rounded-lg w-full h-[180px] object-cover" src={CDN_URL + cloudinaryImageId}/>
          {/* 这里修改了名称的样式 */}
          <h3 className="font-bold text-lg text-wrap">{name}</h3> 
          {/* 这里修改了菜系的样式 */}
          <h4 className="text-wrap">{cuisines.join(", ")}</h4>
          <h4>{avgRating}</h4>
          <h4>{costForTwo}</h4>
       </div>
    )
}

export const withPromotedLabel = (RestaurantCard) => {
  return (props) => {
      return (
         <div>
            <label>Promoted</label>
            <RestaurantCard {...props}/>
         </div>
      )
   }
}
export default RestaurantCard;

这样修改后,你的餐厅卡片里的文本就会乖乖在组件内部自动换行啦~

备注:内容来源于stack exchange,提问作者nidhishree rao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:04:51