我有一个 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”属性,因此当父组件的 local.use_lang 发生更改时,我需要重新渲染组件。
CKEditor 可以通过给它一个强制重新渲染key
prop 等于应强制其重新渲染的值:
<CKEditor key={this.props.local.use_lang} etc />
这样,每当 language prop 发生变化时,React 都会创建一个新的 CKEditor。
请记住,我使用此解决方案是因为 CKEditor 是我使用 npm 安装的外部组件库。如果我正在使用我自己的代码,我只需更改编辑器使用其道具的方式即可。但是,由于我拒绝对外部库代码进行更改,因此这是允许我强制重新渲染而无需触及编辑器代码内部的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)