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

如何为自定义React组件添加高度属性以设置不同文本框高度

实现方案(3种常用方式可选)


方案1:给Textarea组件新增可配置的height属性(推荐,复用性最高)

第一步修改styled组件定义,让它支持接收自定义高度参数,默认值保留原有的80px:

const Textarea = styled.textarea`
  width: 100%;
  border: 1px solid #d3d3d3;
  outline: none;
  resize: none;
  transition: 0.1s ease-out;
  /* 读取传入的height参数,没传就用默认80px */
  height: ${props => props.height || '80px'};
  background-color:white;
`;

第二步修改form.js里「Job Requirements」对应的Textarea代码,传入高度参数即可:

<Label>Job Requirements</Label>
<Textarea
  type="textarea"
  name="requirement"
  focus={isFocused}
  value={requirement}
  onFocus={handleOnFocus}
  onChange={handleTitleChange}
  {/* 新增这行指定高度 */}
  height="40px"
/>

方案2:不修改基础Textarea组件,单独生成定制化变体

如果你的Textarea是公共组件不能随意改动原有定义,可以在当前表单页直接派生一个自定义高度的组件:

// 在form.js顶部导入styled后新增这段代码
const ShortTextarea = styled(Textarea)`
  height: 40px;
`;

然后把「Job Requirements」对应的Textarea替换为ShortTextarea即可,原有其他属性不需要改动。

方案3:按name属性适配(仅适合一次性临时需求)

如果只有这一处特殊高度需求,不想加新属性也不想加新组件,可以直接在styled定义里按name判断高度:

const Textarea = styled.textarea`
  width: 100%;
  border: 1px solid #d3d3d3;
  outline: none;
  resize: none;
  transition: 0.1s ease-out;
  height: ${props => props.name === 'requirement' ? '40px' : '80px'};
  background-color:white;
`;

这种方式不需要改动form.js的代码,但扩展性差,后续新增其他高度需求时不好维护,只适合临时场景使用。

内容的提问来源于stack exchange,提问作者tanmya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 05:06:07