如何使用useState()获取文本区域数据



我读了一页又一页,不确定我做错了什么。我的useState与我的其他输入一起工作。我无法让它与我的文本区域一起工作。

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

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>
</>
)
}

您正在函数外初始化状态,请这样做:此外,您在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。请参阅此处。

需要记住的一些事项:

import React, { useState } from "react";
const OrderItems = () => {
// Always initialise state inside the component
const [commentText,setCommentText] = useState("")
const handleOnSubmit = event => {
event.preventDefault();
console.log(commentText);
}
return (
// onSubmit should just be a reference to handleOnSubmit
<form  id="myForm" onSubmit={handleOnSubmit} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information
</label>
// You can self-close the textarea tag
<textarea 
name="commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value={commentText}
onChange={e => setCommentText(e.target.value)}
/> 
</div>
// Put the button inside the form
<button type = "submit" form ="myForm" className="btn_submit" alt="submit Checkout">
<a href ="/cart/preview"/>
<img src = ""/>
</button>
</form>
);
}

最新更新