微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用draft.js一个文本编辑器,我有两个组件:CreatePost.js,它从后端获取post字段,并用用户输入和{{1}填充状态},其中包含我在TextEditor.js中使用的文本编辑器。文本编辑器应以CreatePost.js onChange的状态填充body字段。

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

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

CreatePost.js

enter image description here

posts.js(控制器)

console.log(body)

CreatePost.js

exports.create = (req,res) => {
  const { title,body,date } = req.body;
  const post = new Post({
    title,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),});
    });
};

TextEditor.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;

解决方法

看来您实际上已经很接近解决这个问题了。使用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)中导入它。转换为原始会返回一个JS对象,因此我们还需要将其转换为字符串,然后才能使用JSON.stringify()将其发送到服务器。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。