我试图允许用户从目录中选择 mp3 轨道并将其显示在屏幕上的播放列表中。到目前为止,我正在使用 for 循环来获取每个文件,但我不确定如何迭代这些文件并为每个文件创建一个新的 {name: file.name}
和将其添加到文件:[]
。现在,当我希望显示所有选定的文件时,只有 for 循环中的最后一个元素通过 li 中的 .map() 函数显示。
这是我的代码:
class Download extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this);
this.inputRef = React.createRef();
this.state = {
files: [],
}
}
handleClick = () => {
const node = this.inputRef.current;
var self = this;
var file;
var name;
node.addEventListener('change', function() {
for(var x = 0, xlen = this.files.length; x < xlen; x++) {
file = this.files[x];
name = file.name;
console.log(name);
//append {name: 'file.name'} x amount of times to files: [] //
}
self.setState({ files: [{ name: name }] });
});
};
render() {
return(
<div className="input">
<input onClick={this.handleClick} id="upload-file" className="inputName" type="file" multiple ref={this.inputRef}/>
<div>
<ul ref={this.ulRef}>
{this.state.files.map((file, index) => (
<li key={index}>
{file.name}
</li>
))}
</ul>
</div>
<output id="list"></output>
</div>
)
};
}
export default Download;
最佳答案
试试这个:
const fileList = [];
for(var x = 0, xlen = this.files.length; x < xlen; x++) {
file = this.files[x];
name = file.name;
console.log(name);
fileList.push({name:name});
//append {name: 'file.name'} x amount of times to files: [] //
}
self.setState({ files: fileList });
关于javascript - 如何将 for 循环中的每个项目添加到 ReactJS 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59289900/