【问题标题】:How can i use component methods in other components如何在其他组件中使用组件方法
【发布时间】:2019-12-26 19:49:39
【问题描述】:

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

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

【问题讨论】:

  • 将方法作为道具传递。
  • 你能解释一下吗?我是 React @Sohan 的新手

标签: javascript reactjs react-component


【解决方案1】:

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

【讨论】:

  • 在构造函数上设置变量notificationDOMRef可能不起作用,在这种情况下覆盖方法'componentDidMount'并设置它
  • 我尝试执行 showError() 方法,我得到了这个: 未捕获的 TypeError:无法读取 null 导出的属性 'current' const addNotification = () => { -> notificationDOMRef.current.addNotification( { 标题:“真棒”,消息:“真棒通知!”,类型:“成功”,插入:“顶部”,容器:“右上角”,animationIn:[“animated”,“fadeIn”],animationOut:[ “动画”,“淡出”],解雇:{持续时间:2000},可解雇:{点击:真}}); }
  • 因为在构造函数上设置变量时你还没有渲染你的组件,这就是为什么你应该重写方法 componentDidMount,或者在 ReactNotification 上使用这个 ref={ ref => notificationDOMRef = ref}
  • 第二个是最好的方法
  • 你能给我看看代码吗?正如我所说,我是新手,我很难弄清楚
【解决方案2】:

我尝试执行 showError() 方法,结果如下: 未捕获的类型错误:无法读取 null 的属性“当前”

这一行:notificationDOMRef.current.addNotification({

【讨论】:

  • 你应该评论答案,不要添加新的答案。
【解决方案3】:

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

<Notifications addNotification={this.addNotification} />

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

【讨论】:

  • 我试过了,但我想在我的方法中使用通知,我该怎么做呢?
猜你喜欢
  • 2021-04-28
  • 1970-01-01
  • 2018-09-27
  • 2017-12-12
  • 2017-12-19
  • 1970-01-01
  • 2018-12-23
  • 2017-11-21
  • 1970-01-01
相关资源
最近更新 更多