我在next中有一个表单,只需输入一个信息,例如页面上的姓名。提交时,我希望浏览器打开一个新的选项卡,其中包含一个包含更多输入的表单,例如姓名、地址、年龄。如何在新选项卡中预先填充名称?
我曾考虑过useContext挂钩,但据我所知,它在选项卡之间不起作用。此时是否需要使用Redux?
编辑:到目前为止我使用localStorage的尝试:
// User inputs name which on submit is
// saved to local storage and /register page is opened
const Home: NextPage = () => {
return (
<Formik
initialValues={{ name: '' }}
onSubmit={(values) =>
localStorage.setItem('name', values.name)
}
>
{() => (
<Form>
<div>
<InputBox
type="text"
id="name"
name="name"
htmlFor="name"
label="Name"
placeholder=""
/>
<button
type="submit"
// ? Not sure using window is the correct way to do this in nextjs
onClick={(event) => window.open('/register', '_blank')}
>
Start KYC
</button>
</div>
</Form>
)}
</Formik>
)
import { Field, Form, Formik } from 'formik'
import { NextPage } from 'next'
import React from 'react'
const Register: NextPage = () => {
let nameInit = ''
React.useEffect(() => {
if (typeof window !== 'undefined') {
console.log('You are on the browser')
// ðï¸ can use localStorage here
} else {
console.log('You are on the server')
// ðï¸ can't use localStorage
}
nameInit = localStorage.getItem('name') ?? ''
console.log(nameInit)
}, [])
return (
<Formik
initialValues={{
name: nameInit,
}}
onSubmit={async (values) => {
console.log(values)
}}
>
{() => (
<Form className="space-y-8 divide-y divide-gray-200">
<div className="sm:col-span-2">
<label
htmlFor="name"
>
First name
</label>
<Field
type="text"
name="name"
id="name"
autoComplete="given-name"
/>
</div>
<div className="flex justify-end">
<button
type="submit"
>
Submit
</button>
</div>
</Form>
)}
</Formik>
)
}
通过查看页面,我可以看到值正在设置中
useEffect
也返回期望值。但是表单仍然没有被填充。。。我猜表单是在执行useEffect之前呈现的吗?当我只是在函数体中编写代码而不是使用useEffect时,它似乎是在localStorage不可用的服务器上执行的。