【问题标题】:React hook form does not work with input from reactstrapReact 钩子表单不适用于来自 reactstrap 的输入
【发布时间】:2021-12-10 22:28:04
【问题描述】:

我对 react-hook-form 和 reactstrap 有疑问。我有这个组件 List.jsx:

import { useContext, useEffect } from "react";
import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider';
import { Link } from "react-router-dom";
import { useForm } from 'react-hook-form';
import { ListGroup, ListGroupItem, Form, FormGroup, Button, Input, Label, Container, Row, Col } from 'reactstrap';





export const Lists = () => {
    const [store, dispatch] = useContext(ListContext);
    const { register, handleSubmit, formState: { errors }, getValues } = useForm();
    const onSubmit = data => addList(data);

    const addList = (data) => {
        console.log(data);
        //dispatch({ type: ADD_LIST, store: store, listName: data.name });

    }

    return (
        <Container>
            <Row>
                <Col>

                    <ListGroup>
                        {store.lists.map((item, key) => {

                            return <ListGroupItem key={key} ><Link to={"/list/" + key}>{item.name}</Link></ListGroupItem>
                        })}
                    </ListGroup>
                </Col>
                <Col>
                    <Form onSubmit={handleSubmit(onSubmit)}>
                        <FormGroup>
                            <Label >Name of new list</Label>
                            <Input type="text" placeholder="name of list" {...register("name", { required: true })} ></Input>
                        </FormGroup>
                        <Button type="submit">Přidat list</Button>
                    </Form>
                </Col>
            </Row>

        </Container>
    );

}

问题是,当我提交表单时,什么也没有发生(addList 不会发生)。但是,当我用来自经典 html 的正常输入替换输入(来自 reactstrap)时,一切似乎都正常。所以问题是来自 reactstrap 的输入。有谁知道如何解决这个问题? 非常感谢!

【问题讨论】:

    标签: javascript html reactjs react-hook-form reactstrap


    【解决方案1】:

    这样试试,看input里面的innerRef

    const { register, handleSubmit, formState: { errors } } = useForm();
    const { ref, ...rest } = register('name')
    const onSubmit = data => console.log(data);
    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <Input type="text" placeholder="Name" innerRef={ref} {...rest} />
    
            <Input type="submit" />
        </form>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2014-09-10
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多