Next.js+React进门记004【在组件函数中传入参数】

计划:将红圈内容改为组件显示,并在组件函数中传入参数,动态显示各页面内容。

在components文件夹下新建Headline.js组件

在index.js页面中使用Headline.js组件

在about.js页面中使用Headline.js组件

组件函数的数据传递测试
①在index.js页面使用的<Headline />组件中,设置属性title="index page"
②在about.js页面使用的<Headline />组件中,设置属性title="about page"
③在Headline.js组件的函数中传入参数,并在浏览器中打印出来

①在index.js页面使用的<Headline />组件中,设置属性title="index page"

②在about.js页面使用的<Headline />组件中,设置属性title="about page"

③在Headline.js组件的函数中传入参数,并在浏览器中打印出来

控制台已经显示数据传递成功,接下来分别在index.js页面和about.js页面中添加page属性,并在各自页面动态显示出来。

修改index.js页面

index.js页面代码

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { Footer } from '../components/Footer'
import Links from '../components/Links'
import Headline from '../components/Headline'

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>Index page</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <Headline title="index page" page="index"/>
       <Links />
      </main>

     <Footer />
    </div>
  )
}

修改about.js页面

about.js页面代码

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Links from '../components/Links'
import { Footer } from '../components/Footer'
import Headline from '../components/Headline'

export default function Home() {
  return (
    <div className={styles.container}>
      <Head>
        <title>About page</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <Headline title="about page" page="about"/>
       <Links />
      </main>

     <Footer />
    </div>
  )
}

修改Headline.js组件

Headline.js组件代码

import styles from '../styles/Home.module.css'

export default function Headline(props) {
  return (
    <div>        

        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">{props.title}</a>
        </h1>

        <p className={styles.description}>
          Get started by editing{' '}
          <code className={styles.code}>pages/{props.page}.js</code>
        </p>

    </div>
  )
}

在浏览器中显示正常,至此计划完成。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值