React unmount并重新安装子组件

jai*_*fps 5 ckeditor reactjs

我有一个npm导入的组件(CKEditor),只关心它在安装时的父组件的状态.即,无论父组件的状态发生什么变化,CKEditor都不会反映这些变化(如果已经安装).

这对我来说是个问题,因为当父组件更改其语言道具时,我需要CKEditor根据父组件的状态进行更改.

有没有办法让我从子组件中卸载并重新装载子组件?例如,有没有办法让我根据父组件的"componentWillReceiveProps"卸载并重新安装子组件?

    import React from 'react';
    import CKEditor from "react-ckeditor-component";

    export default class EditParagraph extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                // an object that has a different html string for each potential language
                content: this.props.specs.content,
            }
            this.handleRTEChange = this.handleRTEChange.bind(this)
            this.handleRTEBlur = this.handleRTEBlur.bind(this)
        }

        /**
         * Native React method 
         *  that runs every time the component is about to receive new props.
         */
        componentWillReceiveProps(nextProps) {
            const languageChanged = this.props.local.use_lang != nextProps.local.use_lang;
            if (languageChanged) {
                // how do I unmount the CKEditor and remount it ???
                console.log('use_lang changed');
            }
        }

        handleRTEChange(evt) {
            // keeps track of changes within the correct language section
        }

        handleRTEBlur() {
            // fully updates the specs only on Blur
        }

        getContent () {
            // gets content relative to current use language
        }

        render() {
            const content = this.getContent();

            // This is logging the content relative to the current language (as expected), 
            // but CKEditor doesn't show any changes when content changes.
            console.log('content:', content);

            // I need to find a way of unmounting and re-mounting CKEditor whenever use_lang changes.
            return (
                <div>
                    <CKEditor 
                        content={content} 
                        events={{
                            "blur": this.handleRTEBlur,
                            "change": this.handleRTEChange
                        }}
                    />
                </div>      
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

jai*_*fps 7

由于CKEditor在安装时仅使用"content"prop,因此当父组件的local.use_lang发生更改时,我需要重新呈现组件.

CKEditor可以通过给它一个key等于应该强制它重新渲染的值的prop来强制重新渲染:

<CKEditor key={this.props.local.use_lang} etc />
Run Code Online (Sandbox Code Playgroud)

这样,只要语言道具发生变化,React就会创建一个新的CKEditor.

请记住,我使用了这个解决方案,因为CKEditor是我用npm安装的外部组件库.如果这是我自己编写的代码,我只会更改编辑器如何使用其道具.但是,由于我拒绝对外部库代码进行更改,因此这是允许我强制重新呈现而无需触及编辑器代码内部的解决方案.