首页 > 解决方案 > TypeError:AddTag 不是函数

问题描述

我正在尝试将标签用户输入添加到现有标签列表中,但我不断收到 TypeError。这是代码的简单版本。我在 App.js 文件中创建了 addTag 并在 Profil.js 中调用它

在 App.js 中

import tag from './tag.json'

const [tagList, setTagList] = useState(tag);
const addTag = (tagInput) => {
      console.log("adding..")
      const newTag = { id : Date.now(), tag: tagInput}
      setTagList([...tagList,newTag])
      console.log("added..")
    }

return (
          <Profile key={e.id} name={e.name} username={e.username} email={e.email} website={e.website} company={e.company.name}
          street={e.address.street} suite={e.address.suite} city={e.address.city} zipcode={e.address.zipcode} 
          addTag={addTag} /> )

在 Profile.js 中

const Profile = (user,{addTag}) => {
const [tagInput, setTagInput] = useState('')
const handleChange = (e) => {
        setTagInput(e.currentTarget.value)
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        addTag(tagInput)
        setTagInput("")
    }
return (
<div className="search">
                    <input type="text" placeholder="Add a tag" value={tagInput} onClick={()=>{
                        setCancelTag(!cancelTag)
                        console.log("search enabled")
                    }} onChange={handleChange} />
                    {cancelTag? null : <button className="cancel-tag" onClick={handleSubmit} >&times;</button>}
                </div>
}

标签: reactjsfunctiontypeerroruse-statereact-functional-component

解决方案


试试下面的。这将解构addTagprop 然后将其余属性分配/传播user给 name 变量:

const Profile = ({ addTag, ...user }) => {

请记住,所有道具都作为第一个参数Profile作为对象传递给函数,其属性与传递给的道具名称匹配Profile


推荐阅读