首页 > 解决方案 > 如何使用 useState() 获取 textarea 数据

问题描述

我一页又一页地阅读,我不确定我做错了什么。我的 useState 与我的其他输入一起使用。我无法让它与我的 textarea 一起使用。

此外,在另一个组件中使用我的数据的最佳方式是什么?

import React, { useState } from "react";

const OrderItems = () => {
const [commentText,setCommentText] = useState("")

const onSubmit = (data) => {
        console.log(data.commentText);
    }
return (
<>
<form  id="myForm" onSubmit={handleSubmit(onSubmit)} >
   <div>
       <label
           htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
                 <textarea 
                     name = "commentTextArea"
                     type="text"
                     id="CommentsOrAdditionalInformation"
                     value = {commentText}
                     onChange={e => setCommentText(e.target.value)}
                      >
               </textarea>
        </div>
</form>

 <button type = "submit" form ="myForm" className="btn_submit" alt = "submit Checkout">
     <a href ="/cart/preview"/>
     <img src = ""/>
 </button>
</>
)
}

标签: reactjsreact-hook-form

解决方案


您正在函数外部初始化状态,请这样做:另外,您在 onSubmit 中记录了错误的状态。

import React, { useState } from "react";
const OrderItems = () => {
 const [commentText,setCommentText] = useState("")

 const handleSubmit = (evt) => {
        evt.preventDefault();
        console.log(commentText);
    }
 return (
 <>
 <form  id="myForm" onSubmit={handleSubmit} >
   <div>
       <label
           htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
                 <textarea 
                     name = "commentTextArea"
                     type="text"
                     id="CommentsOrAdditionalInformation"
                     value = {commentText}
                     onChange={e => setCommentText(e.target.value)}
                      >
               </textarea>
              <input type = "submit" value="Submit" className="btn_submit" alt = "submit Checkout"/>
        </div>
</form>


    
</>
)
}

要在另一个组件中使用数据:如果它是子组件,则将其作为道具传递。否则使用上下文redux等状态管理工具。

另外,对于路由,我建议使用 React Router。参考这里


推荐阅读