Javascript 如何将for循环中的每个项添加到数组中

Javascript 如何将for循环中的每个项添加到数组中,javascript,reactjs,Javascript,Reactjs,我试图允许用户从目录中选择mp3曲目,并将其显示在屏幕上的播放列表中。到目前为止,我正在使用for循环获取每个文件,但我不确定如何遍历这些文件,为每个文件创建一个新的{name:file.name},并将其添加到文件:[]。现在,当我希望显示所有选定的文件时,通过my li中的my.map()函数只显示for循环中的最后一个元素。 这是我的密码: class Download extends React.Component { constructor(props) { sup

我试图允许用户从目录中选择mp3曲目,并将其显示在屏幕上的播放列表中。到目前为止,我正在使用for循环获取每个文件,但我不确定如何遍历这些文件,为每个文件创建一个新的
{name:file.name}
,并将其添加到
文件:[]
。现在,当我希望显示所有选定的文件时,通过my li中的my.map()函数只显示for循环中的最后一个元素。 这是我的密码:

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;
类下载扩展了React.Component{
建造师(道具){
超级(道具)
this.handleClick=this.handleClick.bind(this);
this.inputRef=React.createRef();
此.state={
文件:[],
}
}
handleClick=()=>{
const node=this.inputRef.current;
var self=这个;
var文件;
变量名;
node.addEventListener('change',function()){
对于(var x=0,xlen=this.files.length;x
{this.state.files.map((文件,索引)=>(
  • {file.name}
  • ))} ) }; } 导出默认下载;
    试试这个:

    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 });
    
    const fileList=[];
    对于(var x=0,xlen=this.files.length;x