reactjs - 如何使用 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>
</>
)
}
解决方案
您正在函数外部初始化状态,请这样做:另外,您在 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。参考这里。
推荐阅读
- android - 如何通过 onKeyUp() 求两个 sum 的差值?
- python - projectPoints 返回大量数字
- smtp - 气流:使用电子邮件操作员时无法分配请求的地址错误
- javascript - JSON解析自动排序数字对象键问题
- android - 按钮未显示 Material Design
- java - 如何通过 java 应用程序将字符串发送到焦点字段后台应用程序;例如擅长?
- ionic-framework - Ionic 3:如何使复选框行为像单选按钮
- java - 如何修复 org.apache.spark.SparkException:作业因阶段失败任务和 com.datastax.spark.connector.rdd.partitioner.CassandraPartition 而中止
- c++ - 当数量大于 size_t 类型的最大数量时,如何使用 std::bitset
- webpack - webpack css-loader 转义问题