如何在React中使用状态值动态地向File对象添加新的Properties



我希望是描述性的,假设我有一个文件对象数组

JSONfiledata = [
{
lastModified:123444,
name: 'file1',
size: 0,
type: ""    
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: ""    
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: ""    
}
]

我有一个这个组件,它通过道具接收数据

import React, {useState} from 'react'
const component = ({files}) => {
const [inputValue, setInputValue] = useState('')
const eventHandler = (e) => setInputValue(e.target.value)
const addNewKey = files.map(fileObj => Object.defineProperty(fileObj, 'newKey', {
value: inputValue
}))
return (
{
files.map(fileData => (<div>
{fileData.name}
<input value={inputValue} onChange={setInputValue} />
</div>))
}
)
}

如何更改当前文件对象,并根据inputValue在每个对象上添加一个"newKey",但彼此独立。

我的意思是,在位置0,假设我在输入";这是文件号"1";在位置1"处;这是文件号2";等等

最后,预期输出将是

[
{
lastModified:123444,
name: 'file1',
size: 0,
type: "",
newKey: "this is the file number one"    
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: "",
newKey: "this is the file number two"     
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: "" ,
newKey: "this is the file number three"    
}
]

我构建了一个解决方案:构建另一个组件来单独管理每个文件。像这样:

import React, { useState } from 'react';
import { Map } from './Map';
export const MapList = ({ files }) => {
const [filesState, setFilesState] = useState([...files]);
const handleChange = nObject => {
/**You can compare with a unique id, preferably */
setFilesState(filesState => filesState.map(file => (file.name === nObject.name ? nObject : file)));
};
return (
<div>
{filesState.map(file => (
// If you have an ID you can send in this plance, to be more simple find the object in the handle function
<Map handleChange={handleChange} file={file} />
))}
<h2>Files Change</h2>
{filesState.map(file => (
<div>
<p>
{file.name} {file.newKey && file.newKey}
</p>
</div>
))}
</div>
);
};

在这个包装器组件中,您将使用handleChange函数更新条目数组。

在您可以构建一个组件来管理您的新密钥之后,例如:

import React, { useState } from 'react';
export const Map = ({ file, handleChange }) => {
const [input, setInput] = useState('');
const handleChangeKey = e => {
const { name, value } = e.target;
const nFile = { ...file, [name]: value };
setInput(value);
handleChange(nFile);
};
return (
<div>
<div>
<label htmlFor={file.name}>
<small>Input for: {file.name}</small>{' '}
</label>
<input id={file.name} name='newKey' value={input} onChange={handleChangeKey} type='text' />
</div>
</div>
);
};

它对我有效,我认为这是一个可能不是最好的解决方案,但却是一个简单的解决方案。

const JSONfiledata = [
{
lastModified:123444,
name: 'file1',
size: 0,
type: ""    
},
{
lastModified:123445,
name: 'file2',
size: 0,
type: ""    
},
{
lastModified:123446,
name: 'file3',
size: 0,
type: ""    
}
];
const fileNameToUpdate = 'file2';
const newKey = "file2Key";
const newArray = JSONfiledata.map((item) => {
if (item.name === fileNameToUpdate) {
return {...item, newKey: newKey };
} else {
return item;
}
});
console.log(`newArray==`, newArray);

相关内容

  • 没有找到相关文章

最新更新