简体   繁体   中英

Call a function on parent component - React

I create a Toast component on react, it's show when show() is called, how can I call show() on other component ?

export default class Toast extends Component{
constructor(props){
    super(props)
    this.state={
        show:false
    }
}
show(){       
    this.setState({show:true})
    setTimeout(() => {
        this.setState({show:false})
    }, this.props.time)
}

render(){
    return(
        <div className={`toast ${this.state.show ? "show":""}`} >{this.props.message}</div>
    )
}}

First i'd call show() using ComponentDidMount() on Toast, it's a good strategy ?

<Toast message="test" time={3000} showToast={true}/>


export default class Toast extends Component{
constructor(props){
    super(props)
    this.state={
        show:false
    }
}
show(){ 
  if(this.props.showToast == true){      
    this.setState({show:true})
    setTimeout(() => {
        this.setState({show:false})
    }, this.props.time)
 }
}

render(){
    return(
        <div className={`toast ${this.state.show ? "show":""}`} >{this.props.message}</div>
    )
}}

In the component, you are trying to call toast, set showToast props to true by passing state according to the condition.

In other component,

<Toast message="test" time={3000} showToast={this.state.showToast}/>

this.state.showToast should be defined in state of the component you are calling Toast from.

Let me know, if it works.

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