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

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

我在模态弹出窗口中使用 React 挂钩形式,但在以编辑形式呈现 tinymce 编辑器内容时遇到问题。第一次打开弹出窗口时它工作正常,但是当关闭该弹出窗口并打开其他记录时它会呈现旧数据。

这是我的代码:

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 有 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;

请让我知道缺少什么或有什么问题,以便编辑器不会更新最近的数据,而其他表单字段(如主题)工作正常。 谢谢

您需要添加两个更改,第一个是您需要将 onChange 包装在回调中,其次您应该将来自 Controller 组件的 value prop 作为 editor 中的 value prop 传递,而不是初始值属性。

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}

    />
 )
}

这样你就可以在useEffect中使用react hook form的setValue函数来设置编辑器的内容了。您也不需要将寄存器传递给 TextEditor 组件,因为控制器正在处理您的表单状态更改。

这是一个工作沙箱,向您展示它是如何工作的: https://codesandbox.io/s/tinymce-react-demo-forked-gg7o8?file=/src/index.js