首页 > 解决方案 > 将对象道具传递给 onSelect 回调未按预期工作

问题描述

我正在使用 react-bootstrap 下拉菜单。As per the documentation , the eventKeyprop will be passed to the onSelecthandler when a dropdown item is selected.

我正在尝试设置eventKey一个对象,并将其传递给我的handleSelect(e)处理程序,但是当我console.log()将值传递给我的处理程序时,它给了我一个 string [object Object]

我的组件如下所示:

const CustomDropdown = props => {
  function handleSelect(e) {
    console.log(e); 
    //I expect this to print { name: 'genre', label: 'Genres' } but 
    //it prints '[object Object]'
  }

  return (
    <Dropdown>
      <Dropdown.Toggle as={React.Button} variant="link" id="dropdown-basic">
        {props.text}
      </Dropdown.Toggle>

      <Dropdown.Menu>
        {props.choices.map((choice, i) => (    //choices is an array of objects
          <Dropdown.Item
            key={i}
            eventKey={choice}        //The object I'm passing in. See below
            onSelect={handleSelect}>
            {choice.label}
          </Dropdown.Item>
        ))}
      </Dropdown.Menu>
    </Dropdown>
  );
};

choice对象如下所示:

{
  name: 'genre',
  label: 'Genres',
}

onSelect={handleSelect}但是,如果我用箭头函数替换我的道具onSelect={() => handleSelect(choice)},对象就会正确地传递给 handleSelect,就像我想要的那样。为什么箭头函数方法传递对象,而原始方法没有?

标签: reactjsjsxreact-bootstrap

解决方案


推荐阅读