在 nextjs 中将道具从一个页面传递到另一个页面
passing props from a page to another page in nextjs
我有一个虚拟 project.in 我的项目我有两个页面。(测试 1 和测试 2)我想将一个道具从页面 1 传递到 page2.i 知道我可以使用 useRouter 钩子,但我不不想将此道具设置为查询字符串。
在我的 test1 页面中,我有一个颜色 variable.this 是常量并且有一个黄色 value.i 想在我的 page2 中使用这个颜色作为道具(props.color)
这是我的 test1 页面
import React from 'react';
const Test1 = props => {
const color='yellow';
return (
<div>
test1
</div>
);
};
export default Test1;
这是我的test2页面
import React from 'react';
const Test2 = props => {
return (
<div>
Your color is {props.color}
</div>
);
};
export default Test2;
Props 从父组件传递到它的子组件。您要问的是在同级组件(即页面)之间传递道具,我认为这没有直接的方法。也许您可以尝试使用 React 的上下文 API,这样您的 Test2 就不会使用任何硬编码值。
也许有太多的方法,但对我来说,我认为你可以使用localStorage。
示例:
//in your test1
//foo is the key, bar is the value
localStorage.setItem("foo", "bar")
//in your test 2 you can get the bar by using foo key
const bar = localStorage.setItem("foo", "bar")
console.log(bar)// bar
这里有一个名为 useLocalStorage 的挂钩,您可以使用它或定制您自己的挂钩。
我有一个虚拟 project.in 我的项目我有两个页面。(测试 1 和测试 2)我想将一个道具从页面 1 传递到 page2.i 知道我可以使用 useRouter 钩子,但我不不想将此道具设置为查询字符串。 在我的 test1 页面中,我有一个颜色 variable.this 是常量并且有一个黄色 value.i 想在我的 page2 中使用这个颜色作为道具(props.color) 这是我的 test1 页面
import React from 'react';
const Test1 = props => {
const color='yellow';
return (
<div>
test1
</div>
);
};
export default Test1;
这是我的test2页面
import React from 'react';
const Test2 = props => {
return (
<div>
Your color is {props.color}
</div>
);
};
export default Test2;
Props 从父组件传递到它的子组件。您要问的是在同级组件(即页面)之间传递道具,我认为这没有直接的方法。也许您可以尝试使用 React 的上下文 API,这样您的 Test2 就不会使用任何硬编码值。
也许有太多的方法,但对我来说,我认为你可以使用localStorage。
示例:
//in your test1
//foo is the key, bar is the value
localStorage.setItem("foo", "bar")
//in your test 2 you can get the bar by using foo key
const bar = localStorage.setItem("foo", "bar")
console.log(bar)// bar
这里有一个名为 useLocalStorage 的挂钩,您可以使用它或定制您自己的挂钩。