javascript - 如何将 for 循环中的每个项目添加到 ReactJS 数组中

标签 javascript reactjs

我试图允许用户从目录中选择 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/

相关文章:

java - 使用 Selenium (Java) 与 React 下拉菜单交互 : "other element would receive the click"

javascript - 如何使react-hook-form在一页中使用多个表单?

javascript - 错误 : Incorrect arguments to mysqld_stmt_execute

javascript - NodeJS/Express : Reading header, 之前设置,结果未定义

reactjs - 如何更改 .MuisvgIcon-root 类样式以覆盖 material-ui react 库中的新样式?

json - React Native - 返回 AsyncStorage 中的所有 JSON 数据?

javascript - 即使我可以在开发人员工具(React&Electron)中看到Javascript undefined字段

Javascript 解析 innerhtml

javascript - 在 Codemirror/emmet 中使用 javascript 扩展缩写

javascript - 如果事件尚未停止,如何确保事件不会再次触发?