我对反应还很陌生。到目前为止大约花了 3-4 天的时间来研究它,所以我可能只是做了一些愚蠢的事情。我的问题是我有一个仅包含可以提交的文本区域的表单。现在它位于 jsx 文件中,我试图在提交表单时将其拉入 js 文件中。我正在使用 jQuery,但我没有收到任何与之相关的错误,所以如果有人能指出我正确的方向,我将不胜感激?
/*---App.jsx file---*/
function Create(){
let date = new Date().getMonth()+1 + "/" + new Date().getDate() + "/" + new Date().getFullYear();
const createPost = (
<div className="createBox">
<form id="postForm">
<div className='dateInput'>
<label>Date: {date}</label>
</div>
<br/>
<div className='commentInput'>
<label>Comment: </label>
<br/>
<textarea type='text' className='commentBox' maxLength='2000'/>
</div>
<br/>
<div>
<input className='submitInput' type='submit'/>
</div>
</form>
</div>
)
return createPost;
}
export default App;
/*---JS FILE---*/
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.7.1.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
$("#postForm").submit(() => {
let post = $(".commentBox").val();
console.log("TEST TEST");
console.log(post);
});
/*---index.jsx file---*/
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App/>
);
.createBox {
height: 35vh;
width: 40vw;
margin: 7.5% 52.5%;
position: absolute;
border: 3px solid black;
box-shadow: 0px 0px 20px 0px black;
}
.postForm {
margin: 1% auto;
height: 95%;
width: 95%;
border: 1px solid black;
font-family:'Courier New', Courier, monospace;
font-size: 20px;
}
.dateInput {
margin: 3% 5%;
}
.commentInput {
margin: -4% 5%;
}
.commentBox {
margin-top: 1%;
height: 170px;
width: 96%;
padding: 10px;
white-space: normal;
overflow: scroll;
resize: none;
}
.submitInput {
margin: 2.5% 42.5%;
height: 40px;
width: 80px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Comment Center - Home</title>
</head>
<body id="root">
</body>
</html>
有意见的答案
使用react时不要使用jquery。除了学习基本的 HTML/javascript 之外,此时(2024 年以上)根本不要使用 jquery。
教育答案
$("#postForm")
在运行时返回哪些元素?添加 console.log($("#postForm"))
并检查开发人员工具控制台以查看其中是否有任何元素。我怀疑它的长度为0,因为表单还没有添加到dom中。
潜在的解决方案(未经测试)
您可以尝试将其包装在 jquery 就绪函数中。所有 jquery 代码都应该在就绪函数中。但如果你使用 react,你就没有理由使用 jquery。即使项目是react + jquery,新代码也应该完全忽略jquery并纯粹使用react。