获取渲染元素的组件

时间:2016-10-30 14:19:36

标签: javascript reactjs typescript components element

目前,我正在使用React制作模态系统。 所以我在侧边栏中有一个按钮,我的模态是身体中的div。

我有两个组件在我的应用程序的主要组件的渲染功能中呈现:

  • MyModal
  • MyModalOpenButton

这是我需要的: 当触发MyModalOpenButton的onClick事件时,我需要执行存储在MyModal组件中的函数。

所以我基本上需要将MyModal的ref存储在var。

我该怎么做?

代码:

import * as ReactDOM from "react-dom";
import * as React from "react";

import { MyModal } from "./component/modal/my-modal";
import { SettingsButtons } from "./component/settings-buttons";
import { CustomComponent } from "./custom-component";

class App extends CustomComponent<{}, {}>{
    constructor() {
        super();
    }

    render() {
        return (
            <div>
                <div className="sidebar">
                    <ul>
                        <li>
                            1
                        </li>
                        <li>
                            2
                        </li>
                        <li>
                            3
                        </li>
                    </ul>
                    <SettingsButtons />
                </div>
                <div className="mainContent">

                </div>
                <footer>TODO</footer>
                <MyModal />
            </div>
        );
    }
}

const app: App = ReactDOM.render(<App />, document.querySelector("#root")) as App;

import * as ReactDOM from "react-dom";
import * as React from "react";

import { CustomComponent } from "./../../custom-component";
import { ButtonComponent } from "./button";

export class MyModalOpenButton extends ButtonComponent<{}, {}> {
    constructor() {
        super();
    }

    render() {
        return (
            <li id="open-button" onClick={this.onClick}>
                <i className="fa fa-plus" aria-hidden="true"></i>
            </li>
        );
    }
    onClick(event: React.MouseEvent<HTMLElement>) {
        // Should open the modal
    }
}

1 个答案:

答案 0 :(得分:1)

你还没有分享你的代码,所以我不能给你一个特别适合你案例的答案,但总的来说:

class MyModal extends React.Component<any, any> {
    public render() {
        ...
    }

    public onButtonClick() {
        ...
    }
}

interface MyModalOpenButtonProps {
    onClick: () => void;
}
class MyModalOpenButton extends React.Component<MyModalOpenButtonProps, any> {
    public render() {
        return <button onClick={ this.props.onClick } />
    }
}

class Main extends React.Component<any, any> {
    private myModal: MyModal;

    public render() {
        return (
            <div>
                <MyModalOpenButton onClick={ this.onButtonClick.bind(this) } />
                <MyModal ref={ modal => this.myModal = modal } />
            </div>
        );
    }

    private onButtonClick() {
        this.myModal.onButtonClick();
    }
}