ReactJS中如何读取上传文本文件并替换文件内指定字符串
代码修改方案
你只需要在现有代码基础上做3处调整即可实现需求:
- 在FileReader读取到文件原始内容后,先执行字符串替换逻辑,再把处理后的内容存入组件状态
- 注意
$是正则表达式特殊字符,使用字符串作为参数的replaceAll方法做替换不需要转义,写法最简便 - 要实现文字加粗效果不能直接拼接字符串渲染,需要对替换后的加粗标签做HTML解析,或者拆分内容分段渲染。
可直接运行的修改后代码
import React, { useState } from "react"; export function Upload({ children }) { // 变量名调整为语义化命名,避免歧义 const [fileContent, setFileContent] = useState(""); const handleChange = e => { const fileReader = new FileReader(); fileReader.readAsText(e.target.files[0], "UTF-8"); fileReader.onload = e => { const rawContent = e.target.result; // 全局替换所有匹配的指定字符串,给目标内容包裹加粗标签 const handledContent = rawContent.replaceAll("$E Between $F", "<strong>Between</strong>"); setFileContent(handledContent); }; }; return ( <> <h1>文本文件上传示例</h1> <input type="file" onChange={handleChange} /> <br /> <div> 上传文件内容: {/* 解析HTML标签,实现文字加粗效果 */} <span dangerouslySetInnerHTML={{ __html: fileContent }}></span> </div> </> ); }
安全优化写法(规避XSS风险)
如果上传的文件内容来源不可控,不建议直接使用dangerouslySetInnerHTML,可以把内容按匹配字符串拆分后遍历渲染,不需要手动插入HTML:
import React, { useState } from "react"; export function Upload({ children }) { const [fileContent, setFileContent] = useState(""); const handleChange = e => { const fileReader = new FileReader(); fileReader.readAsText(e.target.files[0], "UTF-8"); fileReader.onload = e => { // 直接存储原始内容,渲染阶段做替换处理 setFileContent(e.target.result); }; }; // 拆分内容分段渲染 const renderContent = () => { if (!fileContent) return null; const contentArr = fileContent.split("$E Between $F"); return contentArr.map((segment, idx) => ( <React.Fragment key={idx}> {segment} {/* 非最后一段时拼接加粗的Between */} {idx !== contentArr.length - 1 && <strong>Between</strong>} </React.Fragment> )); }; return ( <> <h1>文本文件上传示例</h1> <input type="file" onChange={handleChange} /> <br /> <div> 上传文件内容:{renderContent()} </div> </> ); }
内容的提问来源于stack exchange,提问作者ReactNative
相关产品推荐
相关产品推荐

