我试图显示一个表单作为一个弹出,当我点击一个按钮。我是React的新手,我真的不知道从哪里开始。
这是我想要显示的React组件:
import React, {useState} from 'react';
const initialFormValues = {
firstName: '',
lastName: '',
email: '',
phone: '',
message: ''
}
export default function Contact(){
//set up state
const [contacts, setContacts] = useState([]);
const [formValues, setFormValues] = useState(initialFormValues);
//helper function to trach changes in the input
const inputChange= (name, value) => {
setFormValues({...formValues, [name]: value})
}
const onChange = e => {
const {name, value} = e.target;
inputChange(name, value);
}
//post a new contact to the backend eventually, right now just display the contact to the DOM
const postNewContact = newContact => {
setContacts([newContact, ...contacts])
setFormValues(initialFormValues);
}
const formSubmit = () => {
const newContact = {
firstName: formValues.firstName.trim(),
lastName: formValues.lastName.trim(),
email: formValues.email.trim(),
phone: formValues.phone.trim(),
message: formValues.message.trim()
}
postNewContact(newContact)
}
const onSubmit = e => {
e.preventDefault();
formSubmit();
}
return (
<div className='contact container'>
<h1>This is the contact component</h1>
<form id='contact-form' onSubmit={onSubmit}>
<div className='form-group submit'>
<button id='contact-btn'>SUBMIT CONTACT INFO</button>
</div>
<div className='form-group inputs'>
<label>
First Name:
<input
type='text'
value={formValues.firstName}
onChange={onChange}
name="firstName"
/>
</label>
<label>
Last Name:
<input
type='text'
value={formValues.lastName}
onChange={onChange}
name="lastName"
/>
</label>
<label>
Email:
<input
type='email'
value={formValues.email}
onChange={onChange}
name="email"
/>
</label>
<label>
Phone Number:
<input
type='text'
value={formValues.phone}
onChange={onChange}
name="phone"
/>
</label>
<label>
Message:
<input
type='text'
value={formValues.message}
onChange={onChange}
name="message"
/>
</label>
</div>
</form>
</div>
)
}
我想在点击"Contact Us"时将此组件显示为弹出窗口链接:
import React from 'react';
import './footer.css'
function Footer()
{
return (
<div className="Footer">
<div className="container">
<div className="row">
<div className="col">
<h4 className="block ">About Us</h4>
</div>
<div className="col">
<h4 className="block" >Contact</h4>
</div>
<div className="col">
<h4><a className="block" href={"https://www.cdc.gov/coronavirus/2019-ncov/faq.html"}>COVID-19 FAQ</a></h4>
</div>
<div className="col">
<h4 className="block"><a className="block" href={"https://www.cdc.gov/coronavirus/2019-ncov/if-you-are-sick/quarantine.html"}>CDC Guidelines</a></h4>
</div>
</div>
</div>
</div>
);
}
export default Footer;
我该如何做到这一点?我希望弹出窗口显示在点击下面的表单,我希望弹出窗口消失,当用户单击提交按钮。
你可以使用HTML + CSS + Javascript创建一个弹出窗口自定义弹出窗口或使用任何UI框架,如Ant Design,并利用Modal组件。
btn.onclick = function() {
modal.style.display = "block";
}
在react中,组件通常由状态控制。
切换联系人表单可见性所需要的是:
- state/setState为联系人表单可见性设置(true/false)
- 触发联系人表单可见性状态变化的函数
- 用onClick属性在按钮上设置上述功能
通过可见性状态,你可以设置一个条件语句,决定联系人表单的样式是display: none还是block。