我有此提醒组件
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
的电话
我做错了什么,如何使其起作用?
答案 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;