Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应:Can';无法从src文件夹获取本地文件,但可以从公用文件夹获取_Reactjs_Fetch Api - Fatal编程技术网

Reactjs 反应:Can';无法从src文件夹获取本地文件,但可以从公用文件夹获取

Reactjs 反应:Can';无法从src文件夹获取本地文件,但可以从公用文件夹获取,reactjs,fetch-api,Reactjs,Fetch Api,我正在尝试获取本地文件“file.html”,并将其设置为字符串状态。程序无法在src文件夹中找到我的文件,而是在公共文件夹中。如何在src中执行此操作 const [html, setHTML] = useState(""); async function getProjectCode() { const file = "file.html" await fetch(file) .then((response) => re

我正在尝试获取本地文件“file.html”,并将其设置为字符串状态。程序无法在src文件夹中找到我的文件,而是在公共文件夹中。如何在src中执行此操作

const [html, setHTML] = useState("");

async function getProjectCode() {
    const file = "file.html"
    await fetch(file)
    .then((response) => response.text())
    .then((data) => {
        setHTML(data);
    });
} 

对于html文件的静态导入,您可以使用webpack。
如果是动态内容(ajax),则必须将文件从src文件夹移动到公共文件夹。

在codesandbox中添加示例代码以进行调试