React - 使用draftjs 的redux-form initialValues

iph*_*nic 4 javascript reactjs redux redux-form 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>
      );
    }
Run Code Online (Sandbox Code Playgroud)

我有两个字段websiteurlhtmlcontent,该组件websiteurl填充了初始值,但我不知道如何使用在RichTextEditor组件中实现的draft-js Editor 来做到这一点。

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

谢谢。

小智 5

我喜欢为 Rich Editor 的“字段组件”创建一个单独的组件,以免混淆表单组件。个人喜好真的。

<Field name="content" component={EditorField} />
Run Code Online (Sandbox Code Playgroud)

移至 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,
    };  
  }
Run Code Online (Sandbox Code Playgroud)

编写 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 }); 
};
Run Code Online (Sandbox Code Playgroud)

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

<Editor
    {...input}
    onEditorStateChange={this.onChange}
    editorState={editorState} />
Run Code Online (Sandbox Code Playgroud)

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