我有一个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>
)
}
}
发布于 2018-03-10 02:07:56
因为CKEditor只在挂载时使用"content“属性,所以当父组件的local.use_lang发生变化时,我需要重新呈现组件。
可以通过为CKEditor提供一个等于强制它重新渲染的值的key
属性来强制它重新渲染:
<CKEditor key={this.props.local.use_lang} etc />
这样,每当语言属性发生变化时,React都会创建一个新的CKEditor。
请记住,我使用这个解决方案是因为CKEditor是我用npm安装的外部组件库。如果我使用的是我自己的代码,我只会更改编辑器使用其道具的方式。然而,由于我拒绝更改外来库代码,这是一种允许我强制重新呈现而不必触及编辑器代码内部的解决方案。
发布于 2018-03-09 14:23:01
这是因为没有检测到任何更改,因此它不会再次调用render()
,因此也不会再次调用getContent()
。
您可以做的是让内容成为状态的一部分(根据您的构造函数,它已经是状态的一部分),并在use_lang
更新时签入componentWillReceiveProps()
。如果是,那么您可以通过调用this.setState({...rest, content = getContent()};
来更新那里的状态。
然后,您的组件render()
函数应该如下所示
<CKEditor
content={this.state.content}
events={{
"blur": this.handleRTEBlur,
"change": this.handleRTEChange
}}
/>
(顺便说一句,通过调用setState()
,这将触发对render()
的调用,如果检测到任何更改,将显示这些更改。但请注意,这实际上并不是“重新挂载”组件,而仅仅是更新视图。换句话说,在这种情况下,更新状态后将不会调用componentWillMount()
和componentDidMount()
。相反,将调用componentWillUpdate()
和componentDidUpdate()
)。Read more about the component lifecycle here
https://stackoverflow.com/questions/49186927
复制相似问题