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

React实现:原文本框保留内容,另一文本框显示大写文本

解决方案

你只需要新增一个状态来存储转换后的大写文本,同时调整按钮点击逻辑和第二个文本框的绑定即可,以下是修改后的完整代码:

import React from 'react'
import { useState } from 'react'

function TextArea(props) {
    // 新增状态存储转换后的大写文本
    const [upperText, setUpperText] = useState("");

    const handleUpperClick= () => {
        // 将转换后的文本存入upperText,而非覆盖原文本
        let newUpperText = text.toUpperCase();
        setUpperText(newUpperText);
    }

    const handleOnChange= (event) => {
        setText(event.target.value);
    }

    const [text, setText] = useState("Enter the text here please!");

  return (
      <div>
        <h1>{props.heading}</h1>
        <div className="mb-3">
            <label htmlFor="myBox" className="form-label">Example Text Area</label>
            <textarea name="" id="myBox" value={text} onChange={handleOnChange} cols="30" rows="10" className="form-control"></textarea>
        </div>
        <button className="btn btn-primary" onClick={handleUpperClick}>
            Convert to Upper Case
        </button>
        <div className="mb-3">
            {/* 修改label的htmlFor对应新的id */}
            <label htmlFor="upperBox" className="form-label">Capital</label>
            {/* 绑定upperText状态,设置只读避免误改 */}
            <textarea name="" id="upperBox" value={upperText} readOnly cols="30" rows="10" className="form-control"></textarea>
        </div>
        
      </div>
  )
}

export default TextArea

关键修改说明:

  • 新增状态:添加upperText和setUpperText专门存储转换后的大写文本,避免覆盖原输入的text状态。
  • 调整点击逻辑:handleUpperClick不再修改原文本的setText,而是调用setUpperText更新大写文本状态。
  • 修复HTML有效性:将第二个文本框的id改为upperBox,并同步修改对应label的htmlFor属性(原代码两个文本框id重复是无效的HTML写法)。
  • 优化用户体验:给第二个文本框加上readOnly属性,防止用户意外修改转换后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:18:07