如何在其他组件中使用组件方法

时间:2019-08-21 13:49:00

标签: javascript reactjs react-component

我创建了一个通知组件。我想在其他组件中使用它

如何在navbar.js中使用this.addNotification()?我尝试了很多方法,但是没有一个起作用,所以也许这里有人知道做到这一点的最佳方法。我会很高兴为您提供帮助!

   //Notifications.js
import React from "react";
import ReactNotification from "react-notifications-component";
import "react-notifications-component/dist/theme.css";

export default class Notifications extends React.Component {
  constructor(props) {
    super(props);
    this.addNotification = this.addNotification.bind(this);
    this.notificationDOMRef = React.createRef();
  }

  addNotification() {
    this.notificationDOMRef.current.addNotification({
      title: "Awesomeness",
      message: "Awesome Notifications!",
      type: "success",
      insert: "top",
      container: "top-right",
      animationIn: ["animated", "fadeIn"],
      animationOut: ["animated", "fadeOut"],
      dismiss: { duration: 2000 },
      dismissable: { click: true }
    });
  }


  render() {
    return (
      <div className="app-content">
        <ReactNotification ref={this.notificationDOMRef} />
        <button ref={this.addNotification} className="btn btn-primary">
          Add Awesome Notification
        </button>
      </div>
    );
  }
}


//Navbar.js
// I want to use the notifications here, but i don't know how
// this.addNotification() - > this is working in the notifications file, `but not here`

import React from 'react';
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink,
  UncontrolledDropdown,
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem, Container, Row, Col } from 'reactstrap';
import LoginModal from './LoginModal';
import User from './User';

// i just import the class 
import Notifications from './Notifications';

export default class MyNavbar extends User {
  constructor(props) {
    super(props);
    this.toggle = this.toggle.bind(this);
    this.toggleDropDown = this.toggleDropDown.bind(this);

    this.state = {
      isOpen: false,
      userName: this.getUserLogin(),
      userEmail: this.getUserEmail(),
      firstTime: this.getFirstTime(),
      dropdownOpen: false,
      info:""
    };
  }

showError(){
 this.addNotification()
// I want something like this, but i don't know how to do this
 }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  toggleDropDown() {
    this.setState({
      dropdownOpen: !this.state.dropdownOpen
    });
 }


  render(props) {
    return (
      <div>
       <Container>

        <Navbar color="da" light expand="md">
          <NavbarBrand href="/">Pies Fajny Jest</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
          {this.state.userName ?
              <Nav className="ml-auto" navbar>
              <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggleDropDown}>
       <DropdownToggle className="btn btn-danger" caret>
        {this.state.userName}
       </DropdownToggle>
       <DropdownMenu>
         <DropdownItem header>Header</DropdownItem>
         <DropdownItem>Some Action</DropdownItem>
         <DropdownItem disabled>Action (disabled)</DropdownItem>
         <DropdownItem divider />
         <DropdownItem>Foo Action</DropdownItem>
         <DropdownItem>Bar Action</DropdownItem>
         <DropdownItem onClick={ () => this.logout(this) }>Wyloguj</DropdownItem>
       </DropdownMenu>
     </Dropdown>
              </Nav>
             :
              <Nav className="ml-auto" navbar>
              <NavItem className="LoginRegister" >
              <LoginModal
              buttonLabel="Zaloguj się"
              title="Logowanie"
              inputSubmit="Zaloguj się"
              />
              </NavItem>
              <NavItem className="LoginRegister" >
              <LoginModal
              buttonLabel="Zarejestruj się"
              title="Rejestracja"
              inputSubmit="Zarejestruj się"
              register="register"
              />
                  </NavItem>
                  </Nav>}
              </Collapse>
            </Navbar>
           </Container>
          </div>
        );
      }
    }

3 个答案:

答案 0 :(得分:0)

您可以通过方法作为道具,例如

<Notifications addNotification={this.addNotification} />

当您管理this.props.addNotification时,您会在Notifications.js中获得该功能

答案 1 :(得分:0)

尝试使用此功能,但我认为创建通知的最佳方法是使用侦听器。但是我认为这会起作用。 还应避免在构造函数上使用“ .bind()”,而应使用箭头函数。

//Notifications.js
import React from "react";
import ReactNotification from "react-notifications-component";
import "react-notifications-component/dist/theme.css";

// Create a variable 
let notificationDOMRef = null

// export this function and import where you want to use
export const addNotification = () => {
    notificationDOMRef.current.addNotification({
    title: "Awesomeness",
    message: "Awesome Notifications!",
    type: "success",
    insert: "top",
    container: "top-right",
    animationIn: ["animated", "fadeIn"],
    animationOut: ["animated", "fadeOut"],
    dismiss: { duration: 2000 },
    dismissable: { click: true }
    });
}

export default class Notifications extends React.Component {

    render() {
        return (
            <ReactNotification ref={ref => notificationDOMRef = ref} />
        );
    }
}


//Navbar.js
// I want to use the notifications here, but i don't know how
// this.addNotification() - > this is working in the notifications file, `but not here`

import React from 'react';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
UncontrolledDropdown,
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem, Container, Row, Col } from 'reactstrap';
import LoginModal from './LoginModal';
import User from './User';

// just import the class and the function
import Notifications, { addNotification } from './Notifications';

export default class MyNavbar extends User {
constructor(props) {
    super(props);
    this.toggle = this.toggle.bind(this);
    this.toggleDropDown = this.toggleDropDown.bind(this);

    this.state = {
    isOpen: false,
    userName: this.getUserLogin(),
    userEmail: this.getUserEmail(),
    firstTime: this.getFirstTime(),
    dropdownOpen: false,
    info:""
    };
}

showError(){
    // you can use here
    addNotification()
}

toggle() {
    this.setState({
    isOpen: !this.state.isOpen
    });
}

toggleDropDown() {
    this.setState({
    dropdownOpen: !this.state.dropdownOpen
    });
}


render(props) {
    return (
    <div>
    // You need to render your component
    <Notifications />
    <Container>

        <Navbar color="da" light expand="md">
        <NavbarBrand href="/">Pies Fajny Jest</NavbarBrand>
        <NavbarToggler onClick={this.toggle} />
        <Collapse isOpen={this.state.isOpen} navbar>
        {this.state.userName ?
            <Nav className="ml-auto" navbar>
            <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggleDropDown}>
    <DropdownToggle className="btn btn-danger" caret>
        {this.state.userName}
    </DropdownToggle>
    <DropdownMenu>
        <DropdownItem header>Header</DropdownItem>
        <DropdownItem>Some Action</DropdownItem>
        <DropdownItem disabled>Action (disabled)</DropdownItem>
        <DropdownItem divider />
        <DropdownItem>Foo Action</DropdownItem>
        <DropdownItem>Bar Action</DropdownItem>
        <DropdownItem onClick={ () => this.logout(this) }>Wyloguj</DropdownItem>
    </DropdownMenu>
    </Dropdown>
            </Nav>
            :
            <Nav className="ml-auto" navbar>
            <NavItem className="LoginRegister" >
            <LoginModal
            buttonLabel="Zaloguj się"
            title="Logowanie"
            inputSubmit="Zaloguj się"
            />
            </NavItem>
            <NavItem className="LoginRegister" >
            <LoginModal
            buttonLabel="Zarejestruj się"
            title="Rejestracja"
            inputSubmit="Zarejestruj się"
            register="register"
            />
                </NavItem>
                </Nav>}
            </Collapse>
            </Navbar>
        </Container>
        </div>
        );
    }

答案 2 :(得分:0)

我试图执行方法showError(),我得到了这个:  未被捕获的TypeError:无法读取null的属性“当前”

此行:notificationDOMRef.current.addNotification({