简体   繁体   中英

Creating a Alert component which can be called from other components

I have this Alert component

class Alert extends Component {

  constructor() {
    this.state = {
      body: "hello"
    }
  }

  show = (body)=> {
    this.setState({
      body: body
    });
  }
  render() {

    return <div>{this.state.body}</div>
  }

}
export default Alert;

I need to call this Alert like

Alert.show("I am new text");

I did like this which is not working

import Alert from './Alert';
class SomeClass extends Component {

  someFunc = ()=> {
     Alert.show("I am new text");
  }

}

I know its possible, seen calls like toast.warn(...) from react-toastify

Am I doing something wrong, how to make it work?

You need to pass ref to call child method.

// parent component

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

import Alert from "./tab";

class ComponentTwo extends React.Component {
  changeAlert = () => {
    this.refs.Alert.show("I am new text");
  };
  render() {
    return (
      <>
        <div onClick={this.changeAlert}>Click Me</div>
        <Alert ref="Alert" />
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ComponentTwo />, rootElement);

And the child component

import React from "react";

class Alert extends React.Component {
  state = {
    body: "hello"
  };

  show = body => {
    this.setState({
      body: body
    });
  };
  render() {
    return <div>{this.state.body}</div>;
  }
}
export default Alert;

Example here: https://codesandbox.io/s/9lk3r4j64r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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