【问题标题】:React js onClick function in a map function is not recognized无法识别地图函数中的React js onClick函数
【发布时间】:2019-07-04 18:24:09
【问题描述】:

我在 React 中得到了这些数组,我想用它来编写和迭代一堆菜单项。我将我的钩子中的状态默认设置为 false,并使用函数 toggleMyIdOne 和 toggleMyIdTwo 来更新状态。

const [myIdOneToggler, setMyIdOne] = useState(false);
const [myIdOneToggler, setMyIdTwo] = useState(false);

const toggleMyIdOne= () => {
    setMyIdOne(!myIdOneToggler);
}

const toggleMyIdTwo= () => {
    setMyIdTwo(!myIdTwoToggler);
}

function Menu() {
    const menuItems = [
        {
            id: "myIdOne",
            state: "myIdOneToggler",
            name: "toggleMyIdOne",
            setState: "setMyIdOne",
            label: "MyIdOne"
        },
        {
            id: "myIdTwo",
            state: "myIdTwoToggler",
            name: "toggleMyIdTwo",
            setState: "setMyIdTwo",
            label: "MyIdTwo"
        },

再往下,我会返回这个,以便在单击复选框后更新复选框的状态。

{menuItems.map(item => (
    <div className="grid-item">
        <input onClick={item.name} type="checkbox" id={item.id} checked={item.state}/>
        <label htmlFor={item.id}>{item.label}</label>
    </div>

这应该调用 toggleMyIdOnetoggleMyIdTwo 函数。当它不在 map 函数中但在 mapfunction 中时,它可以正常工作并且符合预期,我声明函数名称的方式似乎有问题。

我收到此错误消息:

未捕获的不变违规:预计 onClick 侦听器是 函数,取而代之的是 string 类型的值。

很明显,react 不会从我声明的带有 menuitems 的数组中识别字符串作为函数,但我不知道如何声明它以使其工作。还是不可能这样做以使代码更紧凑。

【问题讨论】:

  • 你试过直接传递函数引用而不是字符串吗?
  • 您收到此错误是因为 name 是一个字符串,并且您将其传递给了 onClick 事件。
  • 您可以发布您想要实现的目标,也许会有解决方法。但我认为没有将函数名称作为字符串传递的解决方案
  • 是的,我实际上想将函数名作为字符串传递。或者以其他方式可以使用我声明的数组来循环遍历项目
  • @ZombieTfk 是的,它直接工作,但我想根据数组有不同的功能

标签: reactjs map-function


【解决方案1】:

在这里你传递一个字符串来点击它应该只接受函数的道具! 要解决这个问题,你可以这样做:

  {menuItems.map(item => (
    <div className="grid-item">
        <input onClick={()=>checkfunction(name)} type="checkbox" id={item.id} checked={item.state}/>
        <label htmlFor={item.id}>{item.label}</label>
    </div>

如果你想触发每个钩子

const checkfunction=name={
if(name==="toggleMyIdOne")
    setMyIdOne(!myIdOneToggler);
else
    setMyIdTwo(!myIdTwoToggler);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多