javascript - 为什么键为空?尽管我创建了它

标签 javascript react-native components key

我使用自定义组件创建了一个基于数组的列表,它可以工作,但不能正常工作,因为我确实尝试在组件实现中发送“key” Prop ,但在组件内部,key Prop 没有存在,只是未定义。

预期的行为是访问组件内的“key” Prop ,并避免我的应用程序上出现“key is not a prop”警告。

这是数据

            data: [
                { key: 1, definition: "Def 1", example: "Example text 1" },
                { key: 2, definition: "Def 2", example: "Example text 2" },
                { key: 3, definition: "Def 3", example: "Example text 3" }
            ]

这是组件实现

createDefinitions = (data) => {
    return data.map((item, index) => {
        return <Definition {...item}/>
    })
}

'item' 是一个对象,其中每个双元都在前一个数组中。实际上,我尝试在这一点上直接添加 'key' 属性,但结果是一样的。

在自定义组件内,我尝试打印 props 对象,但“key”不存在

<Text>{JSON.stringify(props)}</Text>

您可以在此处输入代码 https://snack.expo.io/r1VE3DiQV

预期的行为是获取自定义组件内的关键属性。

谢谢!

最佳答案

tl;dr 您无法访问key通过this.props.key 。如果您需要为 key 设置的值通过不同的名称传递它,例如 id

<小时/>

一旦设置了关键属性,就无法通过 props 访问它。如果您尝试访问它,您将收到以下黄色警告

yellow box warning for accessing key prop

Warning: %s: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop. https://reactjs.org/warnings/special-props.html

我使用了链接解析的实际网址,因为 SO 提示使用缩短的网址

点击警告中的链接会显示以下消息:

Most props on a JSX element are passed on to the component, however, there are two special props (ref and key) which are used by React, and are thus not forwarded to the component.

然后它会告诉您,如果您需要访问该值,则应该将其设置为不同的 prop。

For instance, attempting to access this.props.key from a component (i.e., the render function or propTypes) is not defined. If you need to access the same value within the child component, you should pass it as a different prop (ex: <ListItemWrapper key={result.id} id={result.id} />). While this may seem redundant, it’s important to separate app logic from reconciling hints.

看看你的代码,工作正常,唯一的问题是你试图访问不是通过 props 传递的 key 。如果删除对 props.key 的引用在你的Definition警告应该消失的组件。

关于javascript - 为什么键为空?尽管我创建了它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391124/

相关文章:

javascript - jQuery - 使用 fadeOut 而不破坏元素

reactjs - 如何在 react 导航中将屏幕方向锁定为纵向模式?

javascript - 当我从多个地方导入它时如何创建单例类?

javascript - 使用 Angular 按顺序接收事件

javascript - 根据 HTML 中的选项标签,以不同的语言显示星期几

reactjs - 我在哪里违反了钩子(Hook)规则?

安卓 : how to create componentName in code using <activity-alias>

javascript - 在 React 中编写组件 - MERN 堆栈问题

创建从 TImage 派生的组件时出现 Delphi7Personal EAccessViolation

javascript - JavaScript 中 new Date() 的 Number 方法