繁体   English   中英

React:如何从另一个组件的自身渲染调用一个组件函数?

[英]React: How to call a component function on it's own render from another component?

我正在尝试实现对PESDK(PhotoEditorSDK)的React导入的方法。

我有一个App.js ,它导入HeaderBodyLeftBodyMiddle,而它们之间没有关系。

BodyMiddle.js是呈现的模板组件

// src/components/BodyMiddle/index.js
import React, { Component } from "react";
import "./BodyMiddle.css";

class BodyMiddle extends Component {
    constructor(props){
        super(props);
    }

    handleClick(e) {
        e.preventDefault();
        // Nothing yet
    }

  render() {
    return (
      <div id="BodyMiddle">
        <div><button id="resetEditor" onClick={(e) => this.handleClick(e)}>Reset Editor</button></div>
        <div class="photo-editor-view"></div>
      </div>
    );
  }
}

export default BodyMiddle;

PhotoEditor.js是调用PESDK的组件:

// src/components/PhotoEditor/index.js
import React from 'react'
import ReactDOM from 'react-dom'

window.React = React
window.ReactDOM = ReactDOM

import "./PhotoEditor.css";
import "photoeditorsdk/css/PhotoEditorSDK.UI.ReactUI.min.css";
import PhotoEditorUI from 'photoeditorsdk/react-ui'

class PhotoEditor extends React.Component {
    constructor(props){
        super(props);
    }

    resetEditor(){
        // Empty the image
        return this.editor.ui.setImage(new Image());
    }

    render() {
      const { ReactComponent } = PhotoEditorUI;

      return (
          <div>
              <ReactComponent
              ref={c => this.editor = c}
              license='licence_removed_for_snippet'
              assets={{
                  baseUrl: './node_modules/photoeditorsdk/assets'
              }}
              editor={{image: this.props.image }}
              style={{
                  width: "100%",
                  height: 576
              }} />
          </div>)
    }
}

export default PhotoEditor;

请注意,通过调用以下代码,可以在BodyLeft.js中渲染photo-editor-view div类,并且效果很好:

ReactDOM.render(<PhotoEditor ref={this.child} image={image} />, container);

容器在哪里(我将图像传递到其他地方):

const container = document.querySelector('.photo-editor-view');

我正在努力实现的目标

我想将Reset Button保留在BodyMiddle中,BodyMiddle是独立的,并且是从App.js调用的,以便从我应用程序中的任何位置调用方法resetEditor()上的PhotoEditor组件。

这样,我可以分离相互干扰的模板文件。

我已经进行了研究,但还没有真正找到答案,我知道React可能不是它的库,但是有什么选择? 我很好奇,越来越多的React live应用程序与许多组件交互运行。

感谢您的时间 ! 最好的祝福

您可以在PhotoEditor上使用ref并将其保存在App中,并且在App中可以有一个名为onResetEditor的方法,该方法调用ref.resetEditor

现在,您可以将onResetEditor传递给BodyMiddle或任何其他组件。

在React https://reactjs.org/docs/refs-and-the-dom.html中阅读有关裁判的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM