Создание компонента Alert, который можно вызывать из других компонентов. - PullRequest
0 голосов
/ 04 марта 2019

У меня есть этот компонент Alert

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;

Мне нужно назвать это Alert как

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

Мне понравилось это, но оно не работает

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

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

}

Я знаю, что это возможно, видел звонки типа toast.warn(...) от react-toastify

Я что-то не так делаю, как заставить это работать?

1 Ответ

0 голосов
/ 04 марта 2019

Вам нужно передать ref для вызова дочернего метода.

// 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);

И дочернего компонента

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;

Пример здесь: https://codesandbox.io/s/9lk3r4j64r

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...