React - redux-form initialValues with draftjs



我正在尝试在我的应用程序中使用 draft-js 作为富文本编辑器,使用redux-form,我面临的问题是我无法从draft-js将 initialValues 填充到编辑器中,我的代码看起来像这样

<form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
<Field
name="websiteurl"
placeholder="INSERT WEBSITE URL HERE"
component={this.renderFieldText}
mandatory='true'
/>
<Field
name="htmlcontent"
placeholder="ENTER HTML CONTENT HERE"
component={this.renderRichTextEditor}
/>
<Button bsStyle="primary" type="submit" className="pull-right" loading={this.state.loading}>Save</Button>
</form>

renderRichTextEditor(field){
return (
<RichTextEditor placeholder={field.placeholder}/>
);
}
renderFieldText(field){
var divClassName=`form-group ${(field.meta.touched && field.meta.error)?'has-danger':''}`;
divClassName = `${divClassName} ${field.bsClass}`;
return(
<div className={divClassName}>
<input
className="form-control"
type={field.type}
placeholder={field.placeholder}
{...field.input}
/>
</div>
);
}

我有两个字段websiteurlhtmlcontent,组件websiteurl填充了初始值,但我不知道如何使用在富文本编辑器组件中实现的draft-js编辑器执行此操作。

如果有人取得了这样的成就,请帮忙。

谢谢。

我喜欢为富编辑器的"字段组件"创建一个单独的组件,以免混淆表单组件。真的是个人喜好。

<Field name="content" component={EditorField} />

正在移动到编辑器字段组件...

constructor(props: Props) {
super(props);
// here we create the empty state 
let editorState = EditorState.createEmpty();
// if the redux-form field has a value
if (props.input.value) {
// convert the editorState to whatever you'd like
editorState = EditorState.createWithContent(convertFromHTML(props.input.value));
}
// Set the editorState on the state
this.state = {
editorState,
};  
}

编写 onChange 函数

onChange = (editorState: Object) => {
const { input } = this.props;
// converting to the raw JSON on change
input.onChange(convertToRaw(editorState.getCurrentContent()));
// Set it on the state
this.setState({ editorState }); 
};

现在在渲染函数中,继续放置编辑器组件。传递 Redux Form 输入道具、onChange 函数和编辑器状态。

<Editor
{...input}
onEditorStateChange={this.onChange}
editorState={editorState} />

现在你可以像通常使用redux-form而不使用Draft-js一样设置初始值。

最新更新