[英]Passing data from a functional component to a parent class component react native
[英]Paasing data from a child class component to a parent functional component in react
我正在尝试将数据从基于类的组件传递到基于功能的组件进行反应。
class 组件是一个反应羽毛笔编辑器,我试图在其中获取在编辑器 (editorHtml) 中键入的数据并将数据传递给功能组件。
下面是基于类的组件中的代码
const CustomHeart = () => <span>♥</span>;
function insertHeart() {
console.log(this)
const Quilly = this.quill
const input = document.createElement("input");
input.setAttribute("type", "file");
input.click();
input.onchange = function(){
const cursorPosition = Quilly.getSelection().index;
Quilly.insertText(cursorPosition, "♥");
Quilly.insertEmbed(cursorPosition,"image","https://cdn.pixabay.com/photo/2022/01/05/22/31/woman-6918210_960_720.jpg");
Quilly.setSelection(cursorPosition + 1);
}
}
class Editor extends React.Component {
state = { editorHtml: "" };
handleChange = html => {
this.setState({ editorHtml: html });
};
static modules = {
toolbar: {
container: "#toolbar",
handlers: {
insertHeart: insertHeart
}
}
};
static formats = [
"header",
"font",
"size",
"bold"]
}
render() {
return (
<div className="text-editor">
<CustomToolbar />
<ReactQuill
value={this.state.editorHtml}
onChange={this.handleChange}
placeholder={this.props.placeholder}
modules={Editor.modules}
formats={Editor.formats}
/>
</div>
);
}
export default Editor
对于基于功能的组件
我正在尝试将 editorHtml 的值传递给下面的功能组件
function SendEmail() {
return (
<Editor >
)
}
我知道我可以将其创建为功能组件并在传递数据时使用道具,但由于在上面的 class 组件的 insertHeart 中使用了这个关键字......我无法使用功能方法
您应该在父组件中管理 editorHTML 的editorHTML
并将其传递给Editor
。
<Editor handleChange={this.handleChange} editorHtml={this.state.editorHTML} />
并通过编辑器中的道具访问它:
<ReactQuill
value={this.props.editorHtml}
onChange={this.props.handleChange}
placeholder={this.props.placeholder}
modules={Editor.modules}
formats={Editor.formats}
/>
经过一段时间后,我能够通过使用 this.props 方法访问 class 组件中的 setHtml 方法来获得解决方案。这个 setHtml 方法接受一个字符串......我传递了我从中得到的值编辑器到 setHtml 方法....参见下面的代码来解决问题....
class Editor extends React.Component {
state = { editorHtml: "" };
handleChange = (html) => {
this.setState({ editorHtml: html });
this.props.setHtml(html);
};
}
在 function 组件中,我设置了 setHtml 的 state 并传递了 Html 中的值的值
function SendEmail() {
const [html, setHtml] = useState("");
{console.log(html)}//This would give you the value typed in your editor
<Editor setHtml = {setHtml} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.