如何将 React RichTextEditor class 变成一个函数?

How to turn React RichTextEditor class into a function?

我在我的项目中使用 react-rte 并尝试让文本编辑器工作,但没有成功。我从上面的网站(下面的代码)复制了 class 并试图把它变成一个函数,因为我对它们有更多的经验。我错过了什么?

Class 来自 react-rte-link

class MyStatefulEditor extends Component {
  static propTypes = {
    onChange: PropTypes.func
  };

  state = {
    value: RichTextEditor.createEmptyValue()
  }

  onChange = (value) => {
    this.setState({value});
    if (this.props.onChange) {
      // Send the changes up to the parent component as an HTML string.
      // This is here to demonstrate using `.toString()` but in a real app it
      // would be better to avoid generating a string on each change.
      this.props.onChange(
        value.toString('html')
      );
    }
  };

  render () {
    return (
      <RichTextEditor
        value={this.state.value}
        onChange={this.onChange}
      />
    );
  }
}

这是我的函数:

function MyStatefulEditor ({ values, setValues }) {
  const value = RichTextEditor.createEmptyValue();

  console.log(values, setValues);

  const handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
    value.toString("html");
  };

  return (
    <RichTextEditor
      value={values.bodyText}
      onChange={handleChange("bodyText")}
      required
      id="body-text"
      name="bodyText"
      className={classes.textField}
      type="string"
      multiline
      rows="20"
      variant="filled"
      style={{ minHeight: 410 }}
    />
  );
}

我让它工作了,以防有人在寻找答案!

// values.bodyText has the database information, 
// if I'm not adding a new thing, but editing an old one

<BodyTextEditor
  value={values.bodyText}
  setValue={bodyText => setValues({...values, bodyText })}
/>

函数:

// some things inside RTE are just for styling, delete the id's etc. 

function BodyTextEditor({ value, setValue }) {

  const [editorValue, setEditorValue] =
    React.useState(RichTextEditor.createValueFromString(value, 'markdown'));

  const handleChange = value => {
    setEditorValue(value);
    setValue(value.toString("markdown"));
  };

  return (
    <RichTextEditor
      value={editorValue}
      onChange={handleChange}
      required
      id="body-text"
      name="bodyText"
      type="string"
      multiline
      variant="filled"
      style={{ minHeight: 410 }}
    />
  );
}
import React, { useState } from 'react';
import RichTextEditor from 'react-rte';

const BodyTextEditor = (props) => {
  const [value, setValue] = useState(RichTextEditor.createEmptyValue());
  const onChange = (value) => {
    setValue(value);
    if (props.onChange) {
      props.onChange(value.toString('html'));
    }
  };

  return <RichTextEditor value={value} onChange={onChange} />;
};

export default BodyTextEditor;

您可以将其用作您的子组件。