我目前正在使用React中的styled-components
库作为Form
。该组件发送CCD_ 3请求;创建";点击CCD_ 4。
import { Form, Button } from "react-bootstrap";
import React, { useState, useEffect } from "react";
import styled from "styled-components";
const StyledInput = styled(Form.Control)`
padding: 2px 5px;
width: 150px;
margin-right: 20px;
height: 50px;
`;
function Builder() {
const [name, setName] = useState("");
return (
<GridWrapper>
<h1>Builder</h1>
<Form>
<Form.Row>
<Form.Group controlId="name" bssize="large">
<Form.Label>Probet Name</Form.Label>
<StyledInput
size="sm"
required
value={name}
type="String"
onChange={(e) => setName(e.target.value)}
className="smaller-input"
/>
</Form.Group>
</Form.Row>
</Form>
<Button type="submit" onClick={handleSubmit}>
Create
</Button>
</GridWrapper>
);
}
My question is, I have passed the `required` prop into the `StyledInput` component, yet when I click on the "Create" `Button` it still sends through an empty String. Is there a quick way to validate this using `styled-components` or do I have to write something myself in the `handleSubmit` function?
将type="submit"
的Button
移动到Form
内部,以便进行验证。至于提交,您可以使用Form
的onSubmit
道具来处理它,而不是点击Button
来处理它
<Form onSubmit={handleSubmit}>
<Form.Row>
<Form.Group controlId="name" bssize="large">
<Form.Label>Probet Name</Form.Label>
<StyledInput
size="sm"
required
value={name}
type="String"
onChange={(e) => setName(e.target.value)}
className="smaller-input"
/>
</Form.Group>
</Form.Row>
<Button type="submit">
Create
</Button>
</Form>
请注意,如果您在提交前执行附加逻辑,或者执行XHR而不是重定向,则在处理提交时,可以选择在事件对象上使用preventDefault
示例:
<Form onSubmit={(e)=>handleSubmit(e)}>
function handleSubmit(e) {
e.preventDefault();
//some logic
}
最后,在功能组件的主体之外使用钩子(即const [name, setName] = useState("")
(。这会导致错误-我建议将其移动到function Builder
内部