React - redux-form initialValues with draftjs

时间:2017-07-13 15:23:35

标签: javascript reactjs redux redux-form 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编辑器来实现这一点strong> RichTextEditor 组件..

如果有人取得了这样的成绩,请提供帮助。

感谢。

1 个答案:

答案 0 :(得分:3)

我喜欢为Rich Editor&#34;字段组件&#34;创建一个单独的组件。为了不弄乱表单组件。个人喜好真的。

<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 Form输入道具,onChange函数和编辑器状态。

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

现在你可以像使用没有Draft-js的redux-form那样设置initialValues。