React - 使用 draftjs 的 redux-form initialValues

React - redux-form initialValues with draftjs

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

<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 填充了 initialValues,但我不知道如何使用已实现的 draft-js 编辑器执行此操作在 RichTextEditor 组件中..

如果有人实现了这样的事情,请帮助。

谢谢。

我喜欢为 Rich Editor 的 "field component" 创建一个单独的组件,以免混淆表单组件。个人喜好真的。

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

移至 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 表单输入道具、您的 onChange 函数和编辑器状态。

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

现在您可以像通常使用没有 Draft-js 的 redux-form 一样设置 initialValues。