![](/img/trans.png)
[英]Unable to call parent component function from child component in React
[英]Call a function on parent component - React
我在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>
)
}}
首先我会在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>
)
}}
在该组件中,您尝试调用toast,根据条件传递状态,将showToast道具设置为true。
在其他方面,
<Toast message="test" time={3000} showToast={this.state.showToast}/>
this.state.showToast应该在调用Toast的组件的状态下定义。
让我知道,是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.