【问题标题】:How to use checkValidity with a link button?如何使用带有链接按钮的 checkValidity?
【发布时间】:2020-01-18 09:16:18
【问题描述】:

我有一个表单,其中按钮是一个链接(带有“to”属性),我正在使用 checkValidity() 来使用必需的属性,但是如果我使用 to={{pathname...}} 它会更改为链接而不进行验证

这是我的表格:

<Form id="form">
   <Input required /* ... */></Input>
   <Button type="submit" onClick={this.send} tag={Link}
       to={{pathname: '/accomodations', 
       param: this.state.param}}> 
   </Button>
</Form>

这是验证码:

send(){
   var $myForm = $('#form');

   if(! $myForm[0].checkValidity()){
       $myForm[0].reportValidity()
   }
}

如果我从按钮中删除“tag={Link}”,它会进行验证,但不会更改路径

如果它有“tag={Link}”,它会更改为路径名而无需验证

有人可以帮忙吗?

【问题讨论】:

    标签: javascript reactjs html5-validation


    【解决方案1】:

    您使用的是哪个 UI 框架/工具包?

    Link 是从react-router 导入的吗? (react-router-dom)

    首先,在你的 react 组件中使用 jQuery 可能不是一个好主意。

    如果表单无效,您应该能够停止活动:

    - send() {
    + send(e){
        var $myForm = $('#form');
    
        if(! $myForm[0].checkValidity()){
    +      e.preventDefault();
           $myForm[0].reportValidity()
        }
     }
    

    在您的表单中,您应该为其分配一个 ref 并使用它来代替 jQuery:

    - <Form id="form">
    + <Form ref={form => this.form = form}>
    

    你可以在sendthis.form.current.checkValidity()

    这一切都假设您使用的是类组件。在函数组件中,您无权访问 ref,但您可以使用 useRef 挂钩来创建 refs。


    我会重构这个组件,并将disabled={!this.state.isFormValid} 添加到Button 组件中。您可以创建一个函数,在表单中的任何字段更改时更新this.state.isFormValid

    这是一个如何工作的示例 https://codesandbox.io/embed/lingering-snowflake-p483o

    【讨论】:

    • 你将如何使用disabled={!this.state.isFormValid} 处理这段代码?
    • 是的,它是从 react-router 导入的,谢谢它对我有很大帮助:)
    • 嗨@CatarinaBatista这是一个简单的例子:codesandbox.io/embed/lingering-snowflake-p483o
    猜你喜欢
    • 2017-09-23
    • 2021-04-11
    • 2023-04-04
    • 2020-11-05
    • 2019-04-23
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多