【问题标题】:How can I access props inside of Component in NextJS如何在 NextJS 中访问组件内部的道具
【发布时间】:2021-02-21 12:57:13
【问题描述】:

我是 NextJS 和 React 的新手,所以我设置了一个示例应用程序来学习其中的技巧。我正在尝试访问我传递给组件的一些道具,但它们似乎只能在return() 之外工作。以下是我设置的示例组件,其中包含我可以访问道具和不能访问道具的示例。我有什么遗漏吗?

import React from 'react';
import { InlineTextarea, BlocksControls } from 'react-tinacms-inline'

export function HeroWithVideo({ 
            css_classes, 
            video_url, 
            poster_url, 
            muted, 
            loop, 
            playsinline, 
            autoplay 
}) {

// Works
console.log(muted)

return (
    <div
        className="mt-20 text-center max-w-6xl mx-auto"
    >
        {/* Doesn't Work */}
        {muted}
        <video>

        </video>
        <h1>
            <InlineTextarea name="heading" focusRing={false} />
       </h1>
    </div>
)
}

export const heroWithVideoBlock = {
Component: ({ index, data }) => (
  <BlocksControls
    index={index}
    focusRing={{ offset: 0 }}
    insetControls
>
    <HeroWithVideo {...data} />
  </BlocksControls>
),
template: {
    label: 'Hero with Video',
    defaultItem: {
        headline: 'Default Hero Headline',
    },
    fields: [
        {
            name: 'css_classes',
            label: 'CSS Classes',
            component: 'text',
        },
        {
            name: 'video_url',
            label: 'Video URL',
            component: 'text',
        },
        {
            name: 'muted',
            label: 'Muted',
            component: 'toggle',
        },
        {
            name: 'loop',
            label: 'Loop',
            component: 'toggle',
        },
        {
            name: 'playsinline',
            label: 'Plays Inline',
            component: 'toggle',
        },
        {
            name: 'autoplay',
            label: 'Autoplay',
            component: 'toggle',
        },

    ],
},
}

【问题讨论】:

  • 好吧,我可以通过使用如下条件访问muted 属性:{/* Now Works */} {muted &amp;&amp; &lt;&gt;test&lt;/&gt;} 但是当我尝试将其应用于我的&lt;video {muted &amp;&amp; &lt;&gt;muted&lt;/&gt;}&gt; 元素时,因为属性不起作用。它抛出错误:Unexpected token, expected "..."
  • 好吧,首先我用错了它,它需要是&lt;video muted={muted} loop={loop}&gt;,其次,它似乎有一个关于 muted 参数的错误,并从 2016 年开始做出反应,现在仍然今天左右,即使它没有显示在 DOM 中呈现,但参数仍然有效。 /耸肩

标签: reactjs next.js


【解决方案1】:

你应该这样工作。

export function HeroWithVideo({...data}){

const {css_classes,video_url,poster_url,muted,loop,playsinline,autoplay } = data

}

那么您可以轻松地使用这些道具,例如:

{muted ? <div> </div> : "" }

<div className={css_classes} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2020-10-12
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多