gpt4 book ai didi

reactjs - React 卸载并重新挂载子组件

转载 作者:行者123 更新时间:2023-12-03 13:26:14 28 4
gpt4 key购买 nike

我有一个 npm 导入的组件(CKEditor),它只关心其父组件在安装时的状态。也就是说,无论父组件的状态发生什么变化,如果父组件已经挂载,CKEditor 都不会反射(reflect)这些变化。

这对我来说是一个问题,因为当父组件更改其语言属性时,我需要 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 属性来强制其重新渲染:

<CKEditor key={this.props.local.use_lang} etc />

这样,每当 language prop 发生变化时,React 都会创建一个新的 CKEditor。

请记住,我使用了此解决方案,因为 CKEditor 是我使用 npm 安装的外部组件库。如果我正在使用我自己的代码,我只需更改编辑器使用其 Prop 的方式即可。但是,由于我拒绝对外部库代码进行更改,因此这是允许我强制重新渲染而无需触及编辑器代码内部的解决方案。

关于reactjs - React 卸载并重新挂载子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49186927/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com