我正在尝试在redux-form中使用react-draft-wysiwyg编辑器,一切都可以正常工作,但是唯一的问题是initialValues对于编辑器字段似乎不起作用。
这是我的Form.js:
<form onSubmit={this.props.handleSubmit(this.onSubmit)} autoComplete="off">
<Field name="title" className="form-input" type="text" placeholder="Title" component={this.titleComponent} />
<Field name="description" className="desc" type="text" placeholder="What is your article about ?" component={this.titleComponent} />
<Field name="editor" type="text" component={EditorFieldComponent} />
<button className="form-button" type="submit" value="Submit">{this.props.button}</button>
</form>
这里是EditorFieldComponent.js:
const EditorFieldComponent = (props) => {
const { meta: {touched, error}, input } = props;
return(
<EditorComponent
onChange={input.onChange}
value={input.value}
touched={touched}
error={error}
input = {{...input}}
/>
);
}
这是EditorComponent.js:
class EditorComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
this.props.onChange(
draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
);
}
onEditorStateChange = (editorState) => {
const { onChange, value } = this.props;
const newValue = draftToHtml(convertToRaw(editorState.getCurrentContent()));
if (value !== newValue) {
onChange(newValue);
}
this.setState({
editorState
});
};
render(){
return(
<React.Fragment>
<Editor
editorState={this.state.editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
editorStyle={{ height: "500px", border: "solid 0.1px rgba(0, 0, 0, 0.1)", padding: "10px"}}
onEditorStateChange={this.onEditorStateChange}
toolbar={{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded'/*, 'emoji'*/, 'image', 'remove', 'history'],
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true }
}}
/>
{this.renderError()}
</React.Fragment>
);}
这里是我尝试使用initialValues的地方:
return(
<div>
<Form
initialValues={{title: "some title", description: "some description", editor: "some text"}}
/>
</div>
);
另外,我应该说initialValues在'description'和'title'字段中起作用,只有'editor'字段有此问题。
所以问题似乎出在EditorComponent constructor()
内部,其中editorState
默认设置为空(或者我应该先说)。这可能会覆盖initialValues
字段的Editor
。
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
我没有找到解决此问题的方法,最终还是按预期使用了initialValues
,但是我发现了一种替代方法,可以为编辑器设置一些我们认为合适的HTML字符串的默认值。这是该解决方案的链接:https://github.com/jpuri/react-draft-wysiwyg/issues/357