簡體   English   中英

如何在 React 中使用 state 值動態地將新屬性添加到文件 object

[英]How to add new Properties to File object in React with state value dynamically

我希望是描述性的,假設我有一個文件 Object 數組

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

我有一個通過 props 接收數據的組件

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>))
     }
   )
}

如何改變當前文件 object 並根據 inputValue 在每個文件上添加一個“newKey”,但彼此獨立。

我的意思是,在 position 0 假設我在 position 1 的輸入“這是第一個文件”上寫下“這是第二個文件”等等....

最后,預期的 output 將是

[
    {
      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 function 更新條目數組。

在您可以構建一個組件來管理您的新密鑰之后,例如:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM