![](/img/trans.png)
[英]How do I loop over items in a Javascript array with a for loop, executing each item individually before moving onto the next (until completed)?
[英]How do I add each item from my for loop onto my array ReactJS
我正在嘗試允許用戶從目錄中選擇 mp3 曲目並將其顯示在屏幕上的播放列表中。 到目前為止,我正在使用 for 循環來獲取每個文件,但我不確定如何遍歷文件並為每個文件創建一個新的{name: file.name}
並將其添加到files: []
. 現在,當我想要顯示所有選定的文件時,只有 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 });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.