简体   繁体   English

为什么编辑器字段不以 react-hook-form 呈现最近的数据

[英]Why Editor field not rendering recent data in react-hook-form

I'm using react hook form in modal popup and facing problem to render tinymce editor content in edit form.我在模式弹出窗口中使用反应钩子形式并面临问题以编辑形式呈现 tinymce 编辑器内容。 It is working fine when popup being open first time but it rendering old data when close that popup and open for other record.它在第一次打开弹出窗口时工作正常,但在关闭该弹出窗口并打开其他记录时呈现旧数据。

Here is mycode:这是我的代码:

import TextEditor from '../utils/Editor';

const EditData = props => {

    const uuid = uuidv4();

      const [templateData, setSubmittedTemplate] = useState({});

      const [formData, setFormData] = useState({
        subject: '',
        content: ''
      });

      const { subject, content} = formData;
      const {
        register,
        handleSubmit,
        control,
        errors,
        reset,
        setValue,
        getValues,
        formState: { isSubmitSuccessful }
      } = useForm({ resolver: yupResolver(schema), defaultValues: formData});
      
      const onUpdateData = async(values) => {
        //api to update
      };

      

      useEffect(() => {
          if(props.temp_id){
            api.get(`/api/data/${props.temp_id}`)
            .then(response => {
                setFormData(response.data);
                setValue('subject',response.data.subject);
                setValue('content',response.data.content);
            });
        }
      }, [props.temp_id, reset]);

      
    return (
        <Modal show={props.modalState} onHide={() => props.onHide('editData')}>
                <Form onSubmit={handleSubmit(onUpdateData)}>
                    <Modal.Header closeButton>
                        <div>
                            <Modal.Title>Edit</Modal.Title>
                        </div>
                    </Modal.Header>
                    <Modal.Body>
                        <Form.Row>
                            <Form.Group as={Col} controlId="subject">
                                <Form.Label className="floating-label">Subject</Form.Label>
                                <Form.Control type="text" name="subject" className="custom_input" ref={register}></Form.Control>
                                {errors.subject && <label className="error">{errors.subject?.message}</label>}
                            </Form.Group>
                        </Form.Row>

                        <Form.Row>
                            <Form.Group as={Col} controlId="content">
                                <Form.Label className="floating-label">Content</Form.Label>
                                <Controller
                                    control={control}
                                    name="content"
                                    defaultValue={formData.content}
                                    render={({ onChange, value}) => (
                                        <TextEditor onChange={onChange} initialvalue={value} register={register} />
                                    )}
                                />
                                 {errors.content && <label className="error">{errors.content?.message}</label>}
                            </Form.Group>
                        </Form.Row>

                    </Modal.Body>
                    <Modal.Footer>
                    <Button varient="primary" className="pl-4 pr-4" type="submit">Update</Button>
                    </Modal.Footer>
                </Form>
            </Modal>
    );
}

export default EditData;

TextEditor have tinyMCE configuration code: TextEditor 有 tinyMCE 配置代码:

const TextEditor = props => {

    return (
        <Editor
            className="custom_input"
            ref={props.register}
            initialValue={props.initialvalue}
            init={{
            height: 300,
            menubar: false,
            statusbar:false,
            //inline:true,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code'
            ],
            toolbar:
                'undo redo | formatselect | bold italic | placeholder | forecolor backcolor |  \
                alignleft aligncenter alignright alignjustify | \
                bullist numlist outdent indent | code | removeformat',
            setup: function (editor) {
                //
                }
            }}
            onEditorChange={props.onChange}

        />
    )
}
export default TextEditor;

Please let me know what is missing or something worng so that editor not updating recent data while other form field like subject working fine.请让我知道缺少什么或磨损的东西,以便编辑器不会更新最近的数据,而其他表单字段(如主题)工作正常。 Thanks.谢谢。

You need to add two changes, the first one is that you need to wrap your onChange in a callback, secondly you should pass the value prop that comes from the Controller component as the value prop in the Editor, not the initialValue prop.您需要添加两个更改,第一个是您需要将 onChange 包装在回调中,其次您应该将来自 Controller 组件的 value 道具作为编辑器中的 value 道具,而不是 initialValue 道具。

const TextEditor = props => {
 const handleEditorChange = (editor) => props.onChange(editor);

 return (
    <Editor
        className="custom_input"
        value={props.initialvalue}
        init={{
        height: 300,
        menubar: false,
        statusbar:false,
        //inline:true,
        plugins: [
            'advlist autolink lists link image charmap print preview anchor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table paste code'
        ],
        toolbar:
            'undo redo | formatselect | bold italic | placeholder | forecolor backcolor |  \
            alignleft aligncenter alignright alignjustify | \
            bullist numlist outdent indent | code | removeformat',
        setup: function (editor) {
            //
            }
        }}
        onEditorChange={handleEditorChange}

    />
 )
}

By doing that you can use the setValue function of react hook form in your useEffect to set the editor content.通过这样做,您可以在 useEffect 中使用 react hook 形式的 setValue function 来设置编辑器内容。 You also don't need to pass a register to the TextEditor component because the controller is handling your form state changes.您也不需要将寄存器传递给 TextEditor 组件,因为 controller 正在处理您的表单 state 更改。

Here's a working sandbox to show you how it works: https://codesandbox.io/s/tinymce-react-demo-forked-gg7o8?file=/src/index.js这是一个工作沙箱,向您展示它是如何工作的: https://codesandbox.io/s/tinymce-react-demo-forked-gg7o8?file=/src/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么'react-hook-form'给出空数据? - Why 'react-hook-form' gives empty data? react-hook-form:更新表单数据 - react-hook-form: Update form data 为什么在“react-hook-form”输入元素中添加 ref 会阻止表单呈现? - Why does adding a ref in a `react-hook-form` input element prevent the form from rendering? 来自 react-hook-form 的数据 - Data from react-hook-form 使用 react-hook-form 进行反应 - 当没有数据可用时呈现 output - 错误 map 未定义 - React using react-hook-form - rendering output when no data is available - error map undefined DraftJS React-Hook-Form - 提交编辑器作为输入 - DraftJS React-Hook-Form - submitting Editor as input 如何将 Lexical 与 React-Hook-Form 集成以将编辑器作为输入提交 - How to integrate Lexical with React-Hook-Form for submitting Editor as input 为什么在 react-hook-form 中对动态表单使用 useFieldArray() 时不能关注当前字段? - Why can't I focus on the current field when using useFieldArray() for dynamic form in react-hook-form? 为什么我的确认密码字段根本没有触发验证(react-hook-form) - Why is my confirm password field not firing validation at all (react-hook-form) 使用嵌套数组结构的 react-hook-form 字段数组 - react-hook-form field array using with nested array structure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM