【发布时间】:2020-04-09 02:58:52
【问题描述】:
我正在使用 React 和 TypeScript。
import React from 'react';
import XLSX from 'xlsx';
interface PropsType {
files: File
}
const ParsingFile:React.FC<PropsType> = ({files}) => {
const [file, setFile] = useState(emptyFile);
const [rfile, setRfile] = React.useState<XLSX.WorkBook>();
const readFile = (file:File) =>{
const reader = new FileReader();
reader.onload = (e:any) => {
const bstr = e!.target!.result;
const wb = XLSX.read(bstr, {type: 'binary'});
setRfile(wb);
}
reader.readAsBinaryString(file);
}
return(
<div>
{readfile(file)} // this line
</div>
)
}
这会引发错误,
Type 'void' is not assignable to type 'ReactNode'
The expected type comes from propeprty 'children' which is declared here on type
'DetailedHTMLProps<HTMLDivElement>, HTMLDivElement>'
如果我有的话,
<div>
<React.Fragment>
{readFile(file)}
</React.Fragment>
</div>
它不会抛出错误。
这是我的问题,
1.为什么void函数不能单独使用?
2. 没有其他组件怎么解决?
提前致谢!
编辑
在这个组件(ParsingFile)中,我想要一个读取 excel 文件,解析和写入新的 excel 文件。
【问题讨论】:
-
如果函数什么都不返回,为什么还要在 JSX 中调用呢?
-
是的,
readFile如果你想在那里使用它,需要返回 JSX。到底想做什么? -
在 JSX 内部,我想进行“读取 excel 文件”的过程。
-
JSX 用于渲染 HTML。如果你的函数没有渲染任何东西,那么它的位置肯定不在模板内。您可以在
render函数中调用它,但不要将其包含在模板中。 -
我建议您将这种代码移到一个单独的模块中,该模块仅公开使用方法,而不是将其与 UI 相关代码混合。
标签: javascript reactjs typescript