简体   繁体   English

如何在 map() function 中获取反应道具

[英]How to get react props inside a map() function

Suppose I have a react function with props active .假设我有一个反应 function 与 props active

// About Page
export default function About() {
  return <Menu active="about" />;
}

// Menu Component
function Menu(props) {
  const items = ["home", "about", "services", "contact"];

  return (
    <nav>
      {items.map((item, index) => {
          console.log(props);
        return <li className={`${props.active === item && "active"}`}> {item} </li>;
      })}
    </nav>
  );
}

How do I get the props.active inside the map() function?如何在 map() function 中获取props.active it's returning undefined right now.它现在返回undefined

Converted to snippet, Seems props is getting correctly.转换为片段,似乎道具得到正确。 (not related, but minor fix, if you use && in class name generation, for the falsy condition classname will be "false") (不相关,但小修复,如果您在 class 名称生成中使用&& ,则错误条件类名将是“假”)

 function About() { return <Menu active="about" />; } function Menu(props) { const items = ["home", "about", "services", "contact"]; return ( <nav> {items.map((item, index) => { console.log(props); return ( <li className={`${props.active === item? "active": "inactive"}`}> {item} </li> ); })} </nav> ); } ReactDOM.render(<About />, document.getElementById('app'))
 .active { color: red }.inactive { color: grey }
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="app"> </div>

The above sample code in question works flawlessly.上面有问题的示例代码完美无缺。

In my project, I was actually modifying the wrong page to provide props, thus got {}在我的项目中,我实际上是在修改错误的页面以提供道具,因此得到 {}

So, I'm writing this answer so that other people won't spend time on it.所以,我写这个答案是为了让其他人不会花时间在上面。

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

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