如何在CodePen中使用React函数?

huangapple go评论61阅读模式
英文:

how to use react function in codepen?

问题

Here's the translated content:

<h3>如何在 CodePen 中使用 React 函数?</h3>

我在 CodePen 中编写了一个 React 函数来测试 React hooks,但它不断报错:`Uncaught ReferenceError: require is not defined.`


**我的代码:**

```javascript
import {useState, useEffect, useRef } from 'react';

function Test() {
  const [count, setCount] = useState(0);
  const prevRef = useRef();
  
  useEffect(() => {
    // const ref = useRef();
    console.log('ref----', prevRef.current);
    prevRef.current = count;
  })
  
  return (
    <div>
      <div onClick={() => setCount(count+1)}>+1</div>
      <div>{`count: ${count}`}</div>
      <div>{`precount: ${prevRef.current}`}</div>
    </div>
  )
}

ReactDOM.render(<Test />, document.getElementById("app"));

<details>
<summary>英文:</summary>

&lt;h3&gt;How to use React functions in CodePen?&lt;/h3&gt;

I wrote a react function in CodePem to test React hooks, however it constantly keeps reporting errors: `Uncaught ReferenceError: require is not defined.`


**My Code:**

import {useState, useEffect,useRef } from 'react';

function Test() {
const [count, setCount] = useState(0);
const prevRef = useRef();

useEffect(() => {
// const ref = useRef();
console.log('ref----', prevRef.current);
prevRef.current = count;
})

return (
<div>
<div onClick={() => setCount(count+1)}>+1</div>
<div>{count: ${count}}</div>
<div>{precount: ${prevRef.current}}</div>
</div>
)
}

ReactDOM.render(<Test />, document.getElementById("app"));


</details>


# 答案1
**得分**: 0

你可以通过调整你的 Pen 中的设置来添加一个包。

请参考下面的图片:

[![在这里输入图片描述][1]][1]

通过这样做,它将自动生成必要的导入语句:

```jsx
import React, { useState, useEffect, useRef } from 'https://esm.sh/react@18.2.0';
import ReactDOM from 'https://esm.sh/react-dom@18.2.0';

为了帮助你理解这个过程,我已经在 CodePen 上创建了一个示例代码。你可以参考这个示例来自己实现它。

这里是示例代码的 CodePen 链接:https://codepen.io/camel2243/pen/ExdBRar

英文:

You can add a package by adjusting the settings in your Pen.

Take a look at the following image for reference:

如何在CodePen中使用React函数?

By doing so, it will automatically generate the necessary import statement:

import React, { useState, useEffect, useRef } from &#39;https://esm.sh/react@18.2.0&#39;;
import ReactDOM from &#39;https://esm.sh/react-dom@18.2.0&#39;;

To help you understand this process, I've created a sample code on CodePen. You can refer to this example to implement it yourself.

Here is the codepen link to the sample code: https://codepen.io/camel2243/pen/ExdBRar

huangapple
  • 本文由 发表于 2023年6月1日 10:36:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定