创建一个可以从其他组件调用的Alert组件

时间:2019-03-04 16:09:24

标签: javascript reactjs ecmascript-6

我有此提醒组件

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.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 :(得分:0)

您需要传递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

相关问题