Closed ufohjl closed 6 years ago
braft-editor提供了initialContent,contentId,onChange,onRawChange和onHTMLChange等参数来实现数据控制,但是因为onChange的回调限定为raw或者html,会丢失组件状态,无法实现组件的受控。
braft-editor
initialContent
contentId
onChange
onRawChange
onHTMLChange
raw
html
建议采用完整的状态EditorState,结合经典的defaultValue、value和onChange模式来实现组件的受控与非受控,并配合braft-util来实现editorState和raw或者html之间的相互转换。
EditorState
defaultValue
value
braft-util
editorState
受控组件:
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使用:
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> ) } }
很好的建议,我感觉2.0版本可以做成这样子的
好的 期待:)
新版本已经采用此方式,感谢建议
666
How to set the data when the form is loaded in antd design. I am using version 4.1.5.
braft-editor
提供了initialContent
,contentId
,onChange
,onRawChange
和onHTMLChange
等参数来实现数据控制,但是因为onChange
的回调限定为raw
或者html
,会丢失组件状态,无法实现组件的受控。建议采用完整的状态
EditorState
,结合经典的defaultValue
、value
和onChange
模式来实现组件的受控与非受控,并配合braft-util
来实现editorState
和raw
或者html
之间的相互转换。受控组件:
非受控组件:
结合
antd使用
: