Shl*_*ain 14 javascript reactjs next.js
/demo我的 Next.js 应用程序中有一条路线13,它使用App Router. 但我无法更改页面的标题(我得到的当前标题是 localhost:3000/demo)。
我有以下代码。
/demo/page.js:
'use client'
....
export const metadata = {
title: 'Demo - ModalJS',
};
export default Demo(){
return ...
}
Run Code Online (Sandbox Code Playgroud)
这'use client'正在造成问题,因为当我删除它时,标题会发生变化,但问题是我无法删除它,因为该组件使用onClick它会在没有“使用客户端”的情况下给出错误
里面的代码Demo如下:
export default function Demo() {
const [title, setTitle] = useState("Title of your modal");
const [desc, setDesc] = useState("You description goes here");
const [theme, setTheme] = useState("light");
const handleclick = ()=>{
const modal = new ModalJS( ... stuff related to this library)
modal.show() //trigger this when you want to show modal
}
return <section id={styles.demosection}>
<div className={styles.demotitle}>Demo</div>
<div className={styles.form}>
<label htmlFor="title" className={styles.label}>Title:</label> <br />
<input type="text" name="title" id={styles.title} className={styles.input} value={title} onChange={(e)=>setTitle(e.target.value)}/>
<br /><br />
<label htmlFor="desc" className={styles.label}>Description:</label> <br />
<input type="text" name="desc" id={styles.desc} className={styles.input} value={desc} onChange={(e)=>setDesc(e.target.value)}/>
<br /><br />
<label htmlFor="theme" className={styles.label}>Theme:</label> <br />
<select type="select" name="theme" id={styles.theme} className={styles.input} onChange={(e)=>setTheme(e.target.value)}>
<option value="light">light</option>
<option value="dark">dark</option>
</select>
<br /><br />
</div>
<div className={styles.showbtndiv}>
<button className={styles.showbtn} onClick={()=>handleclick()}>Show Modal</button>
</div>
</section>
}
Run Code Online (Sandbox Code Playgroud)
You*_*mar 20
正如您在文档metadata中所读到的,您不能在客户端组件中使用。这是他们警告这一点的引文:
静态和动态
metadata直通generateMetadata仅在服务器组件中受支持。
因此,您不必将整个页面(或布局)作为客户端组件,而是可以将客户端文件中需要交互的部分移动并将其导入到服务器页面中,正如他们所说:
为了提高应用程序的性能,我们建议尽可能将客户端组件移动到组件树的叶子。
app/demo/page.js在您的情况下,您可以将当前文件的内容移动到app/demo/demo.js文件内,例如,不带metadata, 并导入它:
// app/demo/page.js
import Demo from "./demo";
export const metadata = {
title: 'Demo - ModalJS',
};
export default Page(){
return <div><Demo/></div>
}
Run Code Online (Sandbox Code Playgroud)
// app/demo/demo.js
'use client'
// ....
export default Demo(){
return ...
}
Run Code Online (Sandbox Code Playgroud)
小智 12
由于每个page.js都可以有一个layout.js,因此您可以利用它将元数据添加到该page.js的layout.js中。
在你的情况下,它看起来像这样
/app/demo/page.js- 保持不变
/app/demo/layout.js:
import { Metadata } from "next";
import Page from "./page"; // import your Demo's page
export const metadata: Metadata = {
title: 'Your Title',
description:
"Your Description",
};
export default Page;
Run Code Online (Sandbox Code Playgroud)
将自动添加您的元数据。