公共组件的提取

为什么要提取公共组件

  1. 降低开发难度
  2. 减少开发时间
  3. 易于代码维护

如何提取

  1. 按常规方法完成页面组件开发,这时,公共的部分应该会被划分为一个单独的组件
  2. 将原来的组件代码拷贝至src/components/cxxx.tsx中,并导出
  3. 在使用的页面中导入并使用它

举例代码说明

src/pages/pg001.tsx

import { NextPage } from 'next';
import Head from 'next/head';
import { InputHTMLAttributes, useState } from 'react';

interface IProps {
}

/**
 * 组件示例
 */
const page: NextPage<IProps> = () => {
    return (
        <>
            <Head>
                <title>组件示例</title>
            </Head>
            <C001 title='name'></C001>
            <C001 title='age'></C001>
        </>
    );
};

export default page;

function C001({ title, id, placeholder, ...rest }: InputHTMLAttributes<HTMLInputElement>) {
    const [inputid] = useState(id || Math.random().toString());
    const plchdr = placeholder || 'type here...';
    return <>
        <div>
            <label htmlFor={inputid}>{title}</label>
            <br />
            <input id={inputid} placeholder={plchdr} {...rest} />
        </div>
        <style jsx>{`
label{
border: 0;
}
`}</style>
    </>;
}

新增组件 src/components/c003.tsx

import { InputHTMLAttributes, useState } from 'react';

export default function Input({ title, id, placeholder, ...rest }: InputHTMLAttributes<HTMLInputElement>) {
    const [inputid] = useState(id || Math.random().toString());
    const plchdr = placeholder || 'type here...';
    return <>
        <div>
            <label htmlFor={inputid}>{title}</label>
            <br />
            <input id={inputid} placeholder={plchdr} {...rest} />
        </div>
        <style jsx>{`
label{
border: 0;
}
`}</style>
    </>;
}

导入该组件后,原页面代码src/pages/pg001.tsx

import { NextPage } from 'next';
import Head from 'next/head';
import Input from '../components/c005';

interface IProps {
}

/**
 * 组件示例
 */
const page: NextPage<IProps> = () => {
    return (
        <>
            <Head>
                <title>组件示例</title>
            </Head>
            <Input title='name' />
            <Input title='age' />
        </>
    );
};

export default page;