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
相关产品推荐
相关产品推荐

