使用es6。
我有一个父母和两个孩子的组成部分 第一个子组件(UploadForm)包含一个输入标记,用于将文件上载到服务器 父组件需要知道哪些文件(其中有多少及其名称),计算总文件大小并将结果与其他一些道具一起发送回第二个子组件(状态)。
现在我得到的是Uncaught TypeError: Cannot read property 'refs' of undefined
,来自我的父组件。
我究竟做错了什么?
这是我的父组件
import './App.scss';
import React,
{
Component,
PropTypes
} from 'react';
import ReactDOM from 'react-dom';
import UploadForm from 'elements/uploadForm';
import { Status } from 'elements/status';
class AppLayout extends Component {
constructor(props) {
super(props);
}
getUploadedFiles = () => {
return this.refs.form.refs.uploadInput.files;
}
getUploadedFilesSize = () => {
let sizeTotal = this.props.filesSize,
files_a = this.getUploadedFiles,
files_cnt = files_a.length;
for (let indx = 0; indx < files_cnt; indx++) {
sizeTotal += files_a[indx].size;
}
let size_cnt = sizeTotal + " bytes";
for (let sizeExtensions = ["KB","MB","GB","TB","PB","EB","ZB","YB"],
indx = 0,
approx = sizeTotal / 1024;
approx > 1;
approx /= 1024, indx++
) {
size_cnt = approx.toFixed(3) + " " + sizeExtensions[indx];
}
return size_cnt;
}
render() {
return (
<div id="appWrapper">
<UploadForm ref="form" updateSize={this.getUploadedFilesSize()} >
<Status filesNum={this.getUploadedFiles().length}
filesSize={this.getUploadedFilesSize()}
/>
</UploadForm>
</div>
)
}
}
AppLayout.propTypes = {
filesNum: PropTypes.number.isRequired,
filesSize: PropTypes.number.isRequired
}
AppLayout.defaultProps = {
filesNum: 0,
filesSize: 0
}
export default AppLayout;
这是我的子组件(UploadForm):
import React,
{
PropTypes,
Component
} from 'react';
class UploadForm extends Component {
constructor(props) {
super(props);
}
render() {
const childrenWithProps = React.Children.map(this.props.children, (child) =>
React.cloneElement(child, {
filesNum: this.props.filesNum,
filesSize: this.props.filesSize
})
);
return (
<div>
<form name="uploadForm">
<input id="uploadInput"
type="file"
name="myFiles"
onChange={this.props.updateSize}
multiple
ref="uploadInput"
/>
<input type="submit" value="Send file" />
</form>
{childrenWithProps}
</div>
)
}
}
export default UploadForm;
基本上,<UploadForm>
从父组件获取其道具。然后,它将这些道具传递给它自己的子组件<Status>
。
但是父组件需要从<UploadForm>
组件中获取上传的文件,然后再将这2个道具传递给它:filesNum
和filesSize
。
考虑到我得到的错误,我很困惑如何操作。
父组件从filesNum
中的input元素中获取<UploadForm>
数据,以获取用户上传的文件并呈现其自己的子组件