亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 React 中驗證樣式化組件的非空字符串

在 React 中驗證樣式化組件的非空字符串

慕萊塢森 2023-03-10 13:25:23
我目前正在將styled-componentsReact 中的庫用于Form. 單擊POST“創建”時,組件會發送請求。Buttonimport { 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?   
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

將Buttonof移到type="submit"the 的內部Form,以便進行驗證。至于提交,你可以使用 的onSubmitprop來處理Form,而不是點擊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


查看完整回答
反對 回復 2023-03-10
  • 1 回答
  • 0 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號