繁体   English   中英

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

[英]How can i use component methods in other components

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

如何在我的 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>
        );
      }
    }

您可以将方法作为道具传递,例如

<Notifications addNotification={this.addNotification} />

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

尝试使用它,但我认为创建通知的最佳方法是使用侦听器。 但我认为这会奏效。 还要避免在构造函数上使用“.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>
        );
    }

我试图执行方法 showError() 并且我得到了这个: Uncaught TypeError: Cannot read property 'current' of null

这一行:notificationDOMRef.current.addNotification({

暂无
暂无

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

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