代码之家  ›  专栏  ›  技术社区  ›  Dhruv B.

为什么{text.length}在react中不起作用。js代码。我想要更改状态文本的长度。请帮帮我

  •  0
  • Dhruv B.  · 技术社区  · 2 年前

    从“React”导入React,{useState};

    导出默认函数TextForm(道具){

    const [text,setText]=useState();
    
    const toUppercase=()=>{
        console.log("button is clicked");
        let newText=text.toUpperCase();
        setText(newText);
    }
    
    const changingText=(event)=>{
        setText(event.target.value)
    }
    return(
        <>
        <div className="container">
            <h1>{props.heading}</h1>
            <div className="mb-3">
              <textarea className="form-control" id="txtarea" rows="10" value={text} placeholder="Enter Your text here" onChange={changingText}></textarea>
            </div>
            <button className="btn btn-primary" onClick={toUppercase}>Click to convert to uppercase</button>
        </div>
        <div className="container my-2">
            <h1>Your text summary</h1>
            <p>{text.length} is number of character</p>
        </div>
        </>
    )
    

    }

    这就是它显示的错误[1]: https://i.stack.imgur.com/MeoMH.jpg

    1 回复  |  直到 2 年前
        1
  •  0
  •   Ganesh Rathor    2 年前

    这是你的错误

    setText(...text,event.target.value);
    

    首先存储以前的值,否则添加新值 settext 每次用一个字覆盖