[英]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 ? 我在react上创建一个Toast组件,它在
show()
被调用时show()
,如何在其他组件上调用show()
?
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上使用
ComponentDidMount()
调用show()
,这是一个很好的策略吗?
<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. 在该组件中,您尝试调用toast,根据条件传递状态,将showToast道具设置为true。
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. this.state.showToast应该在调用Toast的组件的状态下定义。
Let me know, if it works. 让我知道,是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.