javascript 使用贴图React渲染 prop

cgyqldqp  于 2023-01-04  发布在  Java
关注(0)|答案(3)|浏览(162)
// Joke.js

import React  from 'react'
export default function Joke(props) {
    return (
        <div>
            {props.setup && <h3>Setup: {props.setup}</h3>}
            <p>Punchline: {props.punchline}</p>
            <hr />
        </div>
    )
}
// Jokes.js

import React  from 'react'
export default [
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    }
]
// App.js

import React from "react"
import Joke from "./Joke"
import jokesData from './Jokes'
export default function App() {
    const jokeElements = jokesData.map(joke => {
        return <Joke setup={joke.setup} punchline={joke.punchline} />
    })
    return (
        <div>
            {jokeElements}
        </div>
    )
}

你好,我刚开始学习react.js。我试图用 prop 和Map渲染运动员,理论上,这是应该的,但它没有工作。
我错过了什么,还是有其他的方式来展示笑话?

ibrsph3r

ibrsph3r1#

如果您不是用scriba编写代码,而是在本地机器上沿着(我知道您是在阅读bob ziroll的React JavaScript库初学者教程)
我对Jokes.js做了一些更改,您不需要在Jokes.js中导入react,因为您不打算使用它。
另外,在本地机器上导出充满对象的数组的效果与在scriba上的效果不同,您需要使用arr定义一个变量,然后将其导出
//Jokes.js

let arr =  [
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    }
]
 
export default arr;
o8x7eapl

o8x7eapl2#

您遇到了导出错误,要正确导出阵列,您必须更改jokesData文件,

let jokesData=[
    {
        setup: "I got my daughter a fridge for her birthday.",
        punchline: "I can't wait to see her face light up when she opens it."
    },
    {
        setup: "How did the hacker escape the police?",
        punchline: "He just ransomware!"
    }
]

export default jokesData;

在App.js中导出数组代码文件,如下所示

import jokesData from "the_name_of_file.js"

如果其他文件导入是正确的,那么这应该工作。

vxbzzdmp

vxbzzdmp3#

您的代码很好,我刚刚将您的代码复制到stackblitz.com,它工作正常。

相关问题