reactjs – React unmount并重新安装子组件
发布时间:2020-12-15 16:20:10 所属栏目:百科 来源:网络整理
导读:我有一个npm导入组件(CKEditor),它只关心其父组件在安装时的状态.即,无论父组件的状态发生什么变化,CKEditor都不会反映这些变化(如果已经安装). 这对我来说是个问题,因为当父组件更改其语言道具时,我需要CKEditor根据父组件的状态进行更改. 我有办法让子组件
我有一个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> ) } } 解决方法
由于CKEditor在安装时仅使用“content”prop,因此当父组件的local.use_lang发生更改时,我需要重新呈现组件.
CKEditor可以通过给它一个等于应该强制它重新渲染的值的关键prop来强制重新渲染: <CKEditor key={this.props.local.use_lang} etc /> 这样,只要语言道具发生变化,React就会创建一个新的CKEditor. 请记住,我使用了这个解决方案,因为CKEditor是我用npm安装的外部组件库.如果这是我自己编写的代码,我只会更改编辑器如何使用其道具.但是,由于我拒绝对外部库代码进行更改,因此这是允许我强制重新呈现而无需触及编辑器代码内部的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |