margox / braft-editor

美观易用的React富文本编辑器,基于draft-js开发
MIT License
4.61k stars 593 forks source link

建议:关于braft-editor实现受控组件和非受控组件的支持 #153

Closed ufohjl closed 6 years ago

ufohjl commented 6 years ago

braft-editor提供了initialContentcontentIdonChangeonRawChangeonHTMLChange等参数来实现数据控制,但是因为onChange的回调限定为raw或者html,会丢失组件状态,无法实现组件的受控。

建议采用完整的状态EditorState,结合经典的defaultValuevalueonChange模式来实现组件的受控与非受控,并配合braft-util来实现editorStateraw或者html之间的相互转换。

受控组件:

import BraftEditor from 'braft-editor'
import util from 'braft-util'

export default class Controlled extends React.Component {

  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
  }

  changeHandler = (editorState) => {
    this.setState({editorState})
    console.log(util.editorStateToRaw(editorState)) // raw
    console.log(util.editorStateToHtml(editorState)) // html
  }

  render() {
    return (
      <BraftEditor
        value={this.state.editorState}
        onChange={this.changeHandler}
      />
    )  
  }
}

非受控组件:

import BraftEditor from 'braft-editor'
import util from 'braft-util'

export default class Uncontrolled extends React.Component {

  changeHandler = (editorState) => {
    console.log(util.editorStateToRaw(editorState)) // raw
    console.log(util.editorStateToHtml(editorState)) // html
  }

  render() {
    return (
      <BraftEditor
        defaultValue={this.props.defaultValue}
        onChange={this.changeHandler}
      />
    )
  }
}

结合antd使用

import BraftEditor from 'braft-editor'
import util from 'braft-util'
import {Form} from 'antd'

@Form.create()
export default class AntDesignForm extends React.Component {

  submitHandler = e => {
    e.preventDefault()
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        let rawContent = util.editorStateToRaw(values.content)
        console.log(rawContent)
        let htmlContent = util.editorStateToHtml(values.content)
        console.log(htmlContent)
      }
    })
  }

  render() {
    let editorState = util.rawToEditorState(this.props.rawContent) // or util.htmlToEditorState(this.props.htmlContent)

    return (
      <Form onSubmit={this.submitHandler}>
        <Form.Item label="详情页">
          {getFieldDecorator('content', {
            initialValue: editorState
          })(
            <BraftEditor placeholder="请输入详情..." />
          )}
        </Form.Item>
      </Form>
    )  
  }
}
margox commented 6 years ago

很好的建议,我感觉2.0版本可以做成这样子的

ufohjl commented 6 years ago

好的 期待:)

margox commented 6 years ago

新版本已经采用此方式,感谢建议

ufohjl commented 6 years ago

666

huseyingoztok commented 4 years ago

How to set the data when the form is loaded in antd design. I am using version 4.1.5.