在 React 中验证样式化组件的非空字符串

我目前正在将styled-componentsReact 中的库用于Form. 单击POST“创建”时,组件会发送请求。Button


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?   


慕莱坞森
浏览 132回答 1
1回答

冉冉说

将Buttonof移到type="submit"the 的内部Form,以便进行验证。至于提交,你可以使用 的onSubmitprop来处理Form,而不是点击Button<Form onSubmit={handleSubmit}>&nbsp; <Form.Row>&nbsp; &nbsp; <Form.Group controlId="name" bssize="large">&nbsp; &nbsp; &nbsp; <Form.Label>Probet Name</Form.Label>&nbsp; &nbsp; &nbsp; <StyledInput&nbsp; &nbsp; &nbsp; &nbsp; size="sm"&nbsp; &nbsp; &nbsp; &nbsp; required&nbsp; &nbsp; &nbsp; &nbsp; value={name}&nbsp; &nbsp; &nbsp; &nbsp; type="String"&nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => setName(e.target.value)}&nbsp; &nbsp; &nbsp; &nbsp; className="smaller-input"&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </Form.Group>&nbsp; </Form.Row>&nbsp; <Button type="submit">&nbsp; &nbsp; Create&nbsp; </Button></Form>请注意,如果您在提交之前执行其他逻辑或执行 XHR 而不是重定向,则可以在处理提交时选择preventDefault在事件对象上使用例子:<Form onSubmit={(e)=>handleSubmit(e)}>function handleSubmit(e) {&nbsp; e.preventDefault();&nbsp; //some logic}const [name, setName] = useState("")最后,您在功能组件主体之外使用钩子(即)。这会导致错误——我建议将它移到里面function Builder
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript