【问题标题】:Can i get the value of my Key inside my react component [duplicate]我可以在我的反应组件中获取我的 Key 的值吗?
【发布时间】:2018-11-02 15:39:46
【问题描述】:

有没有办法可以在我的react component 中访问我的key

   <LessonsLearnedNew
        key={item.id ?item.id[0]:item.tempID}

   />

  class LessonsLearnedNew extends Component {
      constructor(props) {
      console.log(props.key)  // coming as undefined
    }
  }

我找到了这样的解决方法。有没有更好的办法?

<LessonsLearnedNew
            key={item.id ?item.id[0]:item.tempID}
            keyVal={item.id ?item.id[0]:item.tempID}

       />

      class LessonsLearnedNew extends Component {
          constructor(props) {
          console.log(props.key)  // coming as undefined
          console.log(props.keyVal)  // getting the value
        }
      }

【问题讨论】:

  • 首先检查天气,您将其作为 console.log(props) 中的道具。

标签: javascript reactjs


【解决方案1】:

密钥不会传递给组件。
来自DOCS

键作为 React 的提示,但它们不会传递给您的组件。如果您需要在组件中使用相同的值,请将其作为具有不同名称的 prop 显式传递:

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);

所以您的“解决方法”实际上是建议的模式。

【讨论】:

    【解决方案2】:

    Key 是反应的唯一身份。因此,如果您有任何值给另一个组件,则使用 props 传递该值,并且密钥总是如此独特。

     <LessonsLearnedNew
        key={item.id ?item.id[0]:item.tempID} //unique identity
        keyVal={item.id ?item.id[0]:item.tempID} // pass value as a props
      />
    

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2018-04-20
      • 2021-08-27
      • 2021-05-15
      • 1970-01-01
      • 2020-12-01
      • 2011-02-18
      • 2012-04-09
      • 2020-01-03
      相关资源
      最近更新 更多