react-quill에 정렬 스타일을 등록하는 방법

Aug 19 2020

내가 사용하고 반응 - 퀼 NPM 패키지를 동적으로 nextjs에 그것을 가져오고 또한 생성 - 다음 - 응용 프로그램을 보일러를 사용하고 있습니다. 반응 퀼 편집기를 작동시킬 수 있지만 도구 모음에서 정렬 버튼으로 설정된 이미지 스타일 / 단락 스타일을 가져오고 내용 (이미지 / 단락)을 다시 표시 할 수 없습니다.

사용 사례 :

  1. 편집기의 도구 모음에서 이미지 / 단락을 추가하고 정렬을 추가합니다.
  2. 데이터베이스에 편집기 내용 저장
  3. npm 패키지 htmr을 사용하여 데이터베이스에서 react-quill 편집기의 내용을 다시 표시합니다.

예상 : 이미지 / 단락 콘텐츠는 여전히 오른쪽 / 가운데 / 정렬되어야합니다.

실제 : 이미지 / 단락 콘텐츠에 모든 스타일 속성이 제거되었습니다.

아래는 내 코드, nextjs에서 react-quill의 이미지 / 단락 스타일을 등록하는 방법은 내 질문입니다.

import { useState,useEffect } from 'react'
import Router from 'next/router'
import dynamic from 'next/dynamic' 
import { withRouter } from 'next/router'   // used to get access to props of react-dom
import { getCookie,isAuth } from '../../actions/auth';
import { createBlog }  from '../../actions/blog'

// dynamically importing react-quill  
const ReactQuill = dynamic( ()=> import('react-quill'), {ssr:false} )
import '../../node_modules/react-quill/dist/quill.snow.css'

const CreateBlog  = ( {router} ) => {


    const [ body,setBody ] = useState( blogFromLS() )
    const [ values,setValues ] = useState({
        error : '',
        sizeError : '',
        success : '',
        formData : '',
        title : '',
        hidePublishButton : false
    })


    const  { error, sizeError, success, formData, title, hidePublishButton } = values;
    const token = getCookie('token')

    useEffect(()=>{
            setValues({...values, formData: new FormData()})
            initCategories()
            intiTags()
    },[router])

    
    const handleChange = name => e => {
        //console.log(e.target.value)
        const value = name === 'photo' ? e.target.files[0] : e.target.value
        formData.set(name,value)
        setValues({...values, [name]:value, formData : formData , error:''})
    }; 

    const handleBody =  e => {
        //console.log(e)
        setBody(e)
        formData.set('body',e)
        if(typeof window !== 'undefined'){
            localStorage.setItem('blog',JSON.stringify(e))
        }
    }

    const publishBlog =(e) => {
            e.preventDefault();
           // console.log('ready to publish')
           createBlog(formData, token).then(data => {
            if(data.error){
                setValues({...values,error:data.error})
                // console.log('error macha')
            }
                else{
                        setValues({...values,title:'' ,error:'', success:' Blog was Published 
                        successfully '})
                        setBody('')
                        setCategories([]);
                        setTags([])
                    }
            })
    }



    const createBlogForm = () => {
        return <form onSubmit= { publishBlog }>
                <div className="form-group">
                        <label className="text-muted"> Title </label>
                        <input type="text" className="form-control" 
                             value= { title }   onChange={handleChange('title')} ></input>
                </div>

            <div className="form-group">
                <ReactQuill style={{height:'30rem',marginBottom:'8rem'}} value={body} 
                        placeholder="Write here, minimum of 200 charaters is required"
                 modules={CreateBlog.modules} formats={ CreateBlog.formats }  onChange={ handleBody } >
                </ReactQuill>
            </div>

            <div className="form-group">
                <button type="submit" className="btn btn-primary" > Publish </button>
            </div><br></br>

        </form>
    }

    const showError = () => (
        <div className="alert alert-danger" style={{display : error ? '' : 'none'}}> {error} </div>
    )

    const showSuccess = () => (
        <div className="alert alert-success" style={{display : success ? '' : 'none'}}> {success} </div>
    )


    return (
        <div className="container-fluid">
              <div className="row">
                    <div className="col-md-8">
                    { createBlogForm() }
                    <div>
                        {showError()}
                        {showSuccess()}
                    </div>
                    </div>
          
              <div className="col-md-4">
                    <div className="form-group pb-2">
                          <h5>Featured Image</h5>
                                <hr></hr>
                        <small className="text-muted">Max.size upto 2mb</small><br></br>
                         <label className="btn btn-outline-info">
                                    Upload Featured Image
                         <input onChange={handleChange('photo')} type="file" accept="image/*" hidden></input>
                        </label>

                 </div>

                    </div>
              </div>
        </div>
        
    )
}


CreateBlog.modules = {
    toolbar : [
            [{ header:'1' }, {header:'2'}, {header:[3,4,5,6] } , {font:[]} ],
            [{ size:[] }],
            ['bold','italic','underline','strike','blockquote'],
            [{ list:'ordered' }, {list:'bullet'},{'indent': '-1'}, {'indent': '+1'} ],
            [{ align: '' }, { align: 'center' }, { align: 'right' }, { align: 'justify' }],
            ['link','image','video'],
            ['clean'],
            ['code-block']
    ]
};


CreateBlog.formats = [
      'header',
      'font',
      'size',
      'bold',
      'italic',
      'underline',
      'strike',
      'blockquote',
      'list',
      'bullet',
      'indent',
      'align',
      'link',
      'image',
      'video',
      'code-block',
];




export default withRouter(CreateBlog);

답변

3 Nitin Aug 28 2020 at 13:59

내가 시도한 한, Image resize Module 은 Nextjs의 상용구에서 작동하지 않으며 스타일 자체는 콘텐츠를 다시 표시하는 동안 등록되지 않습니다. 상용구를 꺼내거나 웹팩을 사용해야합니다.

Nextjs와 매우 잘 작동하는 반응 형 텍스트 편집기에 SunEditor를 사용하는 것이 좋습니다. SunEditor github 링크 . _document.js 또는 _app.js에서 스타일 시트를 전역으로 가져 오기만하면됩니다.

여기 에서 데모 를 볼 수 있습니다.

james Aug 21 2020 at 22:49

전역 스타일을 등록하려면 pages/_app.js( docs ) 에 넣어야합니다 .

import '../../node_modules/react-quill/dist/quill.snow.css'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

이 CSS 가져 오기를 페이지별로 허용 하는 RFC 가 있습니다 . 또한 이것에 대해 이야기 하는 문제 입니다.