简体   繁体   English

使用 React 功能组件更新 Array 中 object 中的属性

[英]To update a property in object in Array with React functional component

I have an input field which is written in a child component and its inside return function我有一个写在子组件中的输入字段,它的内部返回 function

const EditSectionComponent = ({
    editCaption,
    editName,
}) => {
    const {name,caption} = details;

    return (
        <input
        type="text"
        className="imageNameDetails"
        value={name}
        onChange={e => editName(e.target)}
        />  
    )
}

and in parent Component, it's like在父组件中,就像

  const onEditClick = id => {
    const selectedAsset = All.find(i => i.id === id);
    setDetails(selectedAsset);
}

const [details, setDetails] = useState([]);

const editName = target => {
    setDetails({ ...details, [name]: target.value })
};

Initial page load I can see both caption and name in the text field, but I am not able to change its value初始页面加载我可以在文本字段中看到标题和名称,但我无法更改其值

It's not updating the UI.它不会更新 UI。 Is the right way to reflect the newly edited text in the input field在输入字段中反映新编辑的文本的正确方法

  • Make sure to destructure the details from props in EditSectionComponent .确保从EditSectionComponent中的道具中解构details
  • In your parent, the initial state ie details is defined as an array.在你的父母中,最初的 state 即details被定义为一个数组。 It need to be an object.它必须是 object。
  • Also while doing setDetails , you need to specify the key.同样在执行setDetails时,您需要指定密钥。 (not a dynamic name in your case) (在您的情况下不是动态名称)

Updated code is here:更新的代码在这里:

const EditSectionComponent = ({
    editCaption,
    editName,
    details,
}) => {
    const {name,caption} = details;

    return (
        <input
        type="text"
        className="imageNameDetails"
        value={name}
        onChange={e => editName(e.target)}
        />  
    )
}

const [details, setDetails] = useState({name: '', caption: ''});

const editName = target => {
    setDetails(prev => ({...prev, name: target.value}))
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM