draft.js:文本编辑器从其他组件的状态填充值

拉尼

我正在使用draft.js一个文本编辑器,我有两个组件:CreatePost.js它从后端获取post字段,并用用户输入填充状态,并且TextEditor.js包含一个我正在in中使用的文本编辑器CreatePost.js文本编辑器应bodyCreatePost.jsonChange状态填充该字段

我的问题是如何让文本编辑器填充其他组件中的状态?我需要使用道具吗?

之前,我有一个文本区域,CreatePost.js其中填充body我希望其他组件中的文本编辑器代替它。我试过使用<TextEditor onChange={this.changeHandler} value={body} />in,CreatePost.js但没有用。

console.log(body)在此处输入图片说明

posts.js(控制器)

exports.create = (req, res) => {
  const { title, body, date } = req.body;
  const post = new Post({
    title,
    body,
    date,
    "author.id": req.profile._id,
    "author.name": req.profile.name,
  });
  post
    .save()
    .then((response) => {
      res.send(response);
    })
    .catch((err) => {
      return res.status(400).json({
        error: errorHandler(err),
      });
    });
};

CreatePost.js

class CreatePost extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      body: "",
      createdPost: "",
      error: "",
    };
  }

  changeHandler = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  submitHandler = (e) => {
    e.preventDefault();
    const {
      user: { _id },
    } = isAuthenticated();
    axios({
      url: `${API}/post/new-post/${_id}`,
      method: "POST",
      data: this.state,
    })
      .then((response) => {
        this.setState({ createdPost: this.state.title });
        return response;
      })
      .catch((error) => {
        if (!this.state.title || !this.state.body) {
          this.setState({
            error: "This post must contain a title and a body.",
          });
        }
        console.log(error);
      });
  };

...

  render() {
    const { title, body } = this.state;
    return (
      <>
        <Navbar />
        <Tabs>
          <TabList className="tabs">
            <Tab className="tab">Draft</Tab>
            <Tab className="tab">Preview</Tab>
          </TabList>
          <TabPanel>
            <div className="newpost_container">
              <form className="newpost_form" onSubmit={this.submitHandler}>
                <div className="form-group">
                  <input
                    type="text"
                    placeholder="Title"
                    name="title"
                    className="newpost_field newpost_title"
                    onChange={this.changeHandler}
                    value={title}
                  />
                </div>
                <div className="form-group newpost_body">
                <TextEditor />
                </div>
                <button className="btn publish-post-btn" type="submit">
                  Publish
                </button>
                {this.showSuccess()}
                {this.showError()}
              </form>
            </div>
          </TabPanel>

          <TabPanel>
            <div>
              <h1>{title}</h1>
              <div>{body}</div>
            </div>
          </TabPanel>
        </Tabs>
      </>
    );
  }
}

export default CreatePost;

TextEditor.js

class TextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
    };
    this.plugins = [addLinkPlugin];
  }
  toggleBlockType = (blockType) => {
    this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType));
  };

  onChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(
      this.state.editorState,
      command
    );
    if (newState) {
      this.onChange(newState);
      return "handled";
    }
    return "not-handled";
  };

// onClick for format options

  onAddLink = () => {
    const editorState = this.state.editorState;
    const selection = editorState.getSelection();
    const link = window.prompt("Paste the link -");
    if (!link) {
      this.onChange(RichUtils.toggleLink(editorState, selection, null));
      return "handled";
    }
    const content = editorState.getCurrentContent();
    const contentWithEntity = content.createEntity("LINK", "MUTABLE", {
      url: link,
    });
    const newEditorState = EditorState.push(
      editorState,
      contentWithEntity,
      "create-entity"
    );
    const entityKey = contentWithEntity.getLastCreatedEntityKey();
    this.onChange(RichUtils.toggleLink(newEditorState, selection, entityKey));
  };

  toggleBlockType = (blockType) => {
    this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType));
  };

  render() {
    return (
      <div className="editorContainer">
        <div className="toolbar">
          <BlockStyleToolbar
            editorState={this.state.editorState}
            onToggle={this.toggleBlockType}
          />
          // format buttons
        </div>

        <div>
          <Editor
            placeholder="Post Content"
            blockStyleFn={getBlockStyle}
            editorState={this.state.editorState}
            handleKeyCommand={this.handleKeyCommand}
            onChange={this.onChange}
            plugins={this.plugins}
            placeholder="Post Content"
          />
        </div>
      </div>
    );
  }
}

export default TextEditor;
Thejool

看来您实际上已经很接近解决这个问题了。使用props将变更处理程序发送到时,您走在正确的道路上TextEditor其中一个解决问题的方法是向上移动editorState到你的CreatePost组件,然后传递值和更改处理向下。如果执行此操作,则应从TextEditor文件中删除editorState及其更改处理程序仅通过继续执行您的示例,这样的方法就可以了,我还没有尝试过代码,但是它可以帮助您朝正确的方向发展。

CreatePost.js

constructor(props) {
    super(props);
    this.state = {
      title: "",
      body: EditorState.createEmpty(),
      createdPost: "",
      error: "",
    };
}

....

<TextEditor onChange={(value) => this.setState({ body: value })} editorState={body} />

TextEditor.js

<Editor
  placeholder="Post Content"
  blockStyleFn={getBlockStyle}
  editorState={this.props.editorState}
  handleKeyCommand={this.handleKeyCommand}
  onChange={this.props.onChange}
  plugins={this.plugins}
  placeholder="Post Content"
/>

发布数据时,我们需要访问编辑器的内容而不是EditorState我们可以通过draft.js API来做到这一点(在此处查看更多信息:https ://draftjs.org/docs/api-reference-editor-state/#getcurrentcontent )。不幸的是,这还不够。我们还需要将内容转换为更易于处理的格式。我们可以使用draft.js做到这一点convertToRaw,您还需要从库(https://draftjs.org/docs/api-reference-data-conversion/#converttoraw)中导入该文件Convert to raw返回一个JS对象,因此我们还需要先将该对象转换为字符串,然后才能使用将其发送到服务器JSON.stringify()

axios({
  url: `${API}/post/new-post/${_id}`,
  method: "POST",
  data: {
    ...this.state,
    body: JSON.stringify(convertToRaw(this.state.body.getCurrentContent()))
  }
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法在包含在 React 组件中的富文本编辑器 (react-draft-wysiwyg) 中获取输入的数据

来自分类Dev

Draft.js编辑器为空

来自分类Dev

draft.js:使编辑器内容成为多页

来自分类Dev

无法在 componentDidMount 中加载的 react-draft-wysiwyg 编辑器中编辑文本

来自分类Dev

检测具有特定高度的Draft.js编辑器的结尾

来自分类Dev

检测模糊也失去了Draft.js编辑器的焦点

来自分类Dev

使用OnBlur事件修剪Draft.js编辑器内容

来自分类Dev

检测模糊也失去了Draft.js编辑器的焦点

来自分类Dev

结合使用Draft.js和Reagent

来自分类Dev

在Draft.js中提出要点

来自分类Dev

结合使用Draft.js和Reagent

来自分类Dev

Draft.js 更改默认等宽字体

来自分类Dev

Draft-js 保存和显示 HTML

来自分类Dev

内容更改时,Draft.js / react-draft-wysiwyg DOM的更新缓慢

来自分类Dev

在这里使用useImperativeHandle挂钩对Draft.JS编辑器和Formik进行了证明吗?

来自分类Dev

从 Draft-js-plugins-editor 导入编辑器会导致空项目出现类型错误

来自分类Dev

如何将react-draft不受控制的编辑器内容转换为html?

来自分类Dev

Draft.js中实体内部的文本

来自分类Dev

如何清除Draft-js中的输入字段

来自分类Dev

我无法从draft-js获取html输出?

来自分类Dev

将draft-js与redux-form结合

来自分类Dev

如何获取draft.js识别转义键?

来自分类Dev

draft-js-export-html导出时不包括视频

来自分类Dev

找不到模块:“ draft-js-export-html”

来自分类Dev

使用带有React Hooks的Draft js提及插件

来自分类Dev

无法在 Draft.js 中垂直调整图像大小

来自分类Dev

在Draft.js装饰器中选择文本on装饰器上单击以实现拖放

来自分类Dev

当readOnly属性为true时,如何在Draft.js编辑器中将自定义呈现的块设为只读?

来自分类Dev

在文本编辑器和其他窗口之间切换

Related 相关文章

  1. 1

    无法在包含在 React 组件中的富文本编辑器 (react-draft-wysiwyg) 中获取输入的数据

  2. 2

    Draft.js编辑器为空

  3. 3

    draft.js:使编辑器内容成为多页

  4. 4

    无法在 componentDidMount 中加载的 react-draft-wysiwyg 编辑器中编辑文本

  5. 5

    检测具有特定高度的Draft.js编辑器的结尾

  6. 6

    检测模糊也失去了Draft.js编辑器的焦点

  7. 7

    使用OnBlur事件修剪Draft.js编辑器内容

  8. 8

    检测模糊也失去了Draft.js编辑器的焦点

  9. 9

    结合使用Draft.js和Reagent

  10. 10

    在Draft.js中提出要点

  11. 11

    结合使用Draft.js和Reagent

  12. 12

    Draft.js 更改默认等宽字体

  13. 13

    Draft-js 保存和显示 HTML

  14. 14

    内容更改时,Draft.js / react-draft-wysiwyg DOM的更新缓慢

  15. 15

    在这里使用useImperativeHandle挂钩对Draft.JS编辑器和Formik进行了证明吗?

  16. 16

    从 Draft-js-plugins-editor 导入编辑器会导致空项目出现类型错误

  17. 17

    如何将react-draft不受控制的编辑器内容转换为html?

  18. 18

    Draft.js中实体内部的文本

  19. 19

    如何清除Draft-js中的输入字段

  20. 20

    我无法从draft-js获取html输出?

  21. 21

    将draft-js与redux-form结合

  22. 22

    如何获取draft.js识别转义键?

  23. 23

    draft-js-export-html导出时不包括视频

  24. 24

    找不到模块:“ draft-js-export-html”

  25. 25

    使用带有React Hooks的Draft js提及插件

  26. 26

    无法在 Draft.js 中垂直调整图像大小

  27. 27

    在Draft.js装饰器中选择文本on装饰器上单击以实现拖放

  28. 28

    当readOnly属性为true时,如何在Draft.js编辑器中将自定义呈现的块设为只读?

  29. 29

    在文本编辑器和其他窗口之间切换

热门标签

归档