我在我的项目中使用 React-18.2.0,但收到以下错误
Uncaught Error: createRoot(...): Target container is not a DOM element.
我已经尝试了大部分上传到互联网的可能解决方案,但不幸的是它没有帮助。
main.js 文件是:
import React from 'react';
import { createRoot } from 'react-dom/client';
// eslint-disable-next-line no-unused-vars
const User = (props) => {
const {control, getValues, setValue} = useForm({
defaultValues: props,
});
return (
<React.Fragment>
<UserSignin></UserSignin>
</React.Fragment>
);
};
const UserSignin = (props) => {
return (
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
);
};
window.$(() => {
(() => {
const user = window.$('#user');
if (user.length) {
const root = createRoot(user);
root.render(
<User/>
);
}
})();
});
在html中,我有这个:
<form action="" method="POST" novalidate>
<div id="user"></div>
</form>
```
Can someone help me please?
$
函数返回一个称为“Wrapped Set”的特殊对象。 React 对这些一无所知,所以
createRoot
无法使用它。您需要使用
.get
来访问底层 dom 元素:
const user = window.$('#user');
if (user.length) {
const root = createRoot(user.get(0));
root.render(<User/>);
}
或者您可以使用 document.getElementById (这是内置于浏览器中的,不需要 jquery):
const userEl = document.getElementById("user");
if (userEl) {
const root = createRoot(userEl);
root.render(<User/>)
}