在我的 react.js
应用程序中上传之前,我尝试更改文件名:
方法如下:
onInputChange = (e) =>{
let newFileName='dp';
if(e.target.files.length!==0){
this.state.file=e.target.files[0];
Object.defineProperty(this.state.file.name, 'name', {
writable: true,
value: newFileName
});
console.log(this.state.file);
}
};
但问题是,每当调用此函数时,我都会收到一条错误消息: 在非对象上调用 Object.defineProperty
如何解决这个问题?
最佳答案
您正在 Object.defineProperty
中的字符串基元上定义新属性。 this.state.file.name
是一个字符串基元,而不是一个对象。
const onInputChange = (e) =>{
let newFileName='dp';
if(e.target.files.length!==0){
const file = e.target.files[0];
// file is an object
// Since file.name is read-only, this is not the proper way to change the name
// For a file object writable is already true
Object.defineProperty(file , 'name', {
value: newFileName
});
console.log(file.name);
// Since file name is readonly, and cannot be changed after the File is created
// This is an alternate way to set the name on a copy of the file object
const blob = file.slice(0, file.size, file.type);
newFile = new File([blob], newFileName, {type: file.type});
console.log(newFile.name);
}
};
document.querySelector("#fileInput").addEventListener("change", onInputChange);
Upload here:
<input type="file" name="test" id="fileInput"/>
此外,要更新状态,不要直接改变 this.state
,而是使用 setState()
方法来更新它。
关于javascript - Object.defineProperty 在我的 React.js 应用程序中调用非对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996898/