useState and useHooks in HTML



首先,我不能使用"创建react应用程序";命令。

所以在这里,我试图将我的react代码添加到一个纯HTML文件中。

以下是我的HTML和js文件代码。

有人能告诉我为什么我的钩子和setState不能正常工作吗?

请指导我解决它。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>

我的like_button.js代码

'use strict';
const e = React.createElement;
const LikeButton = () => {
const [liked, setLiked] = useState(false);
useEffect(() => {
if (liked) {
return <div>You liked this</div>;
}
}, [liked]);
return e('button', { onClick: () => setLiked(true) }, 'Like');
};
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

您尝试从useEffect返回时,从useEffects返回是为了清理效果,。

事实上,您甚至不需要使用useEffect,只需要根据喜欢的状态更改渲染即可。

此外,您展示的示例代码具有JSX语法,因此不确定您为什么使用createElement,但我创建了下面没有它的示例,以防万一。。

例如。

const e = React.createElement;
const {useState, useEffect} = React;
const LikeButton = () => {
const [liked, setLiked] = useState(false);
return e('button', { onClick: () => setLiked(true) },   
liked ? 'You Like this..' : 'Like');
};
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

最新更新