老实说,我不太了解这一行的语法:
const {ItalicButton, BoldButton, UnderlineButton, OLButton, ULButton, H2Button} = richButtonsPlugin;
这称为解构,是一种从对象(或数组)中提取数据并将它们放入变量的方法。如果你这样写,你会得到同样的结果:
const ItalicButton = richButtonsPlugin.ItalicButton
const BoldButton = richButtonsPlugin.BoldButton
const UnderlineButton = richButtonsPlugin.UnderlineButton
...and so on
这就是您收到错误的原因:
Module build failed: Duplicate declaration "ItalicButton"
您已经创建了const ItalicButton
两次变量(实际上您已经对所有变量进行了创建)。
我认为您应该做的是:
将带有丰富按钮的编辑器变成自己的组件。它可能看起来像这样:
import Editor from 'draft-js-plugins-editor';
import createRichButtonsPlugin from 'draft-js-richbuttons-plugin';
const richButtonsPlugin = createRichButtonsPlugin();
const { ItalicButton, BoldButton, UnderlineButton, OLButton, ULButton, H2Button } = richButtonsPlugin;
const plugins = [
richButtonsPlugin
//...other plugins
];
export default class MyEditor extends Component {
render() {
return (
<div>
<div className="myToolbar">
<BoldButton/>
<ItalicButton/>
<UnderlineButton/>
<OLButton/>
<ULButton/>
<H2Button/>
</div>
<Editor
editorState={this.props.editorState}
handleChange={this.props.handleChange}
plugins={plugins}
// ...other props
/>
</div>
);
}
}
假设您将此组件放入一个名为my-editor.js
. 现在您可以在任何地方重复使用它,如下所示:
import MyEditor from './my-editor.js';
import { EditorState } from 'draft-js';
export default class App extends Component {
state = {
editorState: EditorState.createEmpty(),
};
handleChange = (editorState) => {
this.setState({ editorState })
}
render() {
return (
<div>
<MyEditor
editorState={this.state.editorState}
handleChange={this.handleChange}
/>
</div>
);
}
}
如果您在同一页面上需要它们的多个实例,您可以创建一个这样的数组editorStates
:
export default class App extends Component {
state = {
editorStates: [EditorState.createEmpty(), EditorState.createEmpty()]
};
handleChange = (index) => (editorState) => {
const currentStates = this.state.editorStates
const updatedStates = currentStates[index] = editorState
this.setState({ editorStates: updatedStates })
}
render() {
return (
<div>
{this.state.editorStates.map((editorState, index) =>
<MyEditor
editorState={this.state.editorState}
handleChange={this.handleChange(index)}
/>
})
</div>
);
}
}
我没有尝试运行此代码,但无论哪种方式,它都应该为您指明正确的方向。希望它有所帮助,如果有什么不清楚或不起作用,请告诉我!