gpt4 book ai didi

reactjs - 用值预填充 React 表单

转载 作者:行者123 更新时间:2023-12-05 02:58:00 25 4
gpt4 key购买 nike

我想在 Post 的 React 中创建编辑表单,所以我的工作流程是这个获取帖子,设置表单的状态,然后显示它......我试图在功能组件中实现它,因为它很容易使用 graphql那里

import React, { useState } from 'react';
import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';
import useForm from 'react-hook-form';

const GET_POST = gql`
query getPost($id: String!) {
getPost(id: $id) {
id
title
content
excerpt
author {
name
}
}
}
`;

const EditPost = (props) => {
// here Im using postId to fetch post
const PostID = props.history.location.state.id;
// Im using react-hook-form
const { register, errors, reset, handleSubmit } = useForm();
let POST = { title: '', author: '', content: '', image: '', excerpt: '' };
//set initial state of form
const [values, setValues] = useState({
title: POST.title, author: POST.author, content: POST.content, image: POST.image, excerpt: POST.excerpt
});


const { data, loading, error } = useQuery(GET_POST, {
variables: { id: PostID },
});

if (loading) return <p>LOADING</p>;
if (error) return <p>ERROR</p>;

const fetchedPost = data.getPost;
// here is a problem I would like when post is fetched to set those values to state & then use it to make form reactive ???
if (fetchedPost) {
const { title, author, content, image, excerpt } = fetchedPost;

}

return (
<div className="edit-form">
<h2>Edit Post</h2>
<fieldset>
<form>
<p className="form-group">
<label htmlFor="title">Post Title: </label>
<input type="text" name="title" id="name"
value={values.title}
aria-invalid={errors.title ? 'true' : 'false'}
aria-describedby="error-title-required error-title-maxLength"
ref={register({ required: true, maxlength: 20 })}
placeholder="Name" />
<span>{errors.title && 'Title is required'} </span>
</p>

</form>
</fieldset>

</div>);
}


export default EditPost;

问题是当我获取帖子时,我不知道如何设置表单的状态以及如何使表单具有反应性???

最佳答案

参见文档:https://github.com/react-hook-form/react-hook-form/blob/fa5e71ca5eef76ae29b9cda774061051e5182162/examples/customValidation.tsx


const intialValues = {
firstName: 'bill',
lastName: 'luo',
email: 'bluebill1049@hotmail.com',
age: -1,
};
      <input
defaultValue={intialValues.firstName}
name="firstName"
placeholder="bill"
ref={register({
validate: value => value !== 'bill',
})}
/>

关于reactjs - 用值预填充 React 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59462289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com