【发布时间】:2019-09-09 04:42:39
【问题描述】:
我一直在尝试从子组件 A 向父组件 C 发送回调,以在父组件 C 中设置状态!此状态将发送到另一个子组件 B。我在 A 中有一个链接组件,它调用 B 中的组件,但子组件需要来自父组件的状态,当我单击 A 中的链接时,没有调用 Back但我希望它被调用。
Class C extends react.Component
{
constructor(props: any)
{
super(props);
this.state={
somestate: '',
}
}
CallBack(somestate:string)
{
this.Setstate({somestate, somestate},()=>{console.log(this.state.somestate);});
}
render()
{
return(
<A CallBack={this.CallBack} />
<Route path='/somestate' >
<B somestate={this.state.somestate} />
</Route>
)
}
}
Class A extends React.Component
{
constructor(props: any)
{
super(props);
}
callback()
{
this.props.CallBack();//causing errror when i click Link tag
}
render()
{
return(
<Link to='/somestate'>
<button onClick={this.callback()}>click me</button>
</Link>
)
}
}
Class B extends React.Component
{
constructor(props: any)
{
super(props);
}
render()
{
return(
<div>
this.props.somestate;
</div>
)
}
}
我无法在道具中回调。我猜我们不能同时使用回调父和链接。那么如何实际使用呢。
【问题讨论】:
-
您可以删除链接并添加“this.props.history.push('/somestate');”在你的回调函数中
-
另外你应该bind your methods 或者使用ES6箭头函数并更正this.setState
标签: reactjs typescript react-router