在 reactjs 中从一个组件共享价值到另一个组件

问题描述

为此我使用了“React Draft Wysiwyg”。在下面的代码中,我想访问 desktop.js 文件中变量 value editor.js 文件的值。我该怎么做?

editor.js:



export default class TextEditor extends Component {
render(){
  return(){
        <textarea
          disabled
         value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
        ></textarea>
    
      
    );
  }
}

desktop.js:

export const Desktop = () => {

    return (
      
        <div className="splitScreen">
            <TextEditor/>

        </div>
}

解决方法

首先,您需要将一个函数作为来自桌面组件的 TextEditor 中的道具传递。

像这样 <TextEditor onChange={this.onChange}>

在桌面组件中声明一个方法如下

onChange = (value) => {
  console.log(value);
}

现在像这样在 onEditorStateChange 方法中的 TextEditor 组件中调用此方法

 onEditorStateChange = (editorState) => {
    this.setState({
      editorState,});
    this.props.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent()));
  };
,

我建议在 desktop.js 中使用 useState,同时将 textValue 的状态和 setState 函数作为道具传递给 TextEditor 组件:

import React,{ useState } from "react";

export const Desktop = () => {
  const [textValue,setTextValue] = useState("");

  return (
    <div className="splitScreen">
      <TextEditor textValue={textValue} setTextValue={setTextValue} />
    </div>
  );
};

然后使用 TextEditor 中的两个 props:

import React,{ Component } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState,convertToRaw } from "draft-js";
import "./editor.css";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html";

export default class TextEditor extends Component {
  state = {
    editorState: EditorState.createEmpty(),};

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

  render() {
    const { editorState } = this.state;

    // here you set the textValue state for the parent component
    this.props.setTextValue(
      draftToHtml(convertToRaw(editorState.getCurrentContent()))
    );

    return (
      <div className="editor">
        <Editor
          editorState={editorState}
          toolbarClassName="toolbarClassName"
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
          onEditorStateChange={this.onEditorStateChange}
        />
        <textarea
          disabled
          text_value={this.props.textValue} // here you use the textValue state passed as prop from the parent component
        ></textarea>
      </div>
    );
  }
}