我有一个组件AppBarRight。单击一个按钮,我有一个后端函数调用,之后,它应该让它的父AppBar渲染一个组件MyList。下面的代码不起作用。请帮忙!
export default class AppBar extends React.Component {
constructor(props) {
super(props);
this.state = { RenderList: false }
this.handleRenderList = this.handleRenderList.bind(this);
}
handleRenderList() {
this.setState({ RenderList: true })
}
render() {
return (
<div>
<AppBarLeft/>
<AppBarRight handler={this.handleRenderList}/>
{this.state.RenderList ? <MyList/> : null}
</div>
);
}
}
export default class AppBarRight extends React.Component{
constuctor(props) {
super(props);
this.state={success: false}
this.handleOnClick=this.handleOnClick.bind(this);
}
handleOnClick(){
getDetails(cred).then( (loginresp) => {
this.setState({ success: true} );}
}
render(){
return(
<Button Onclick={this.handleOnClick}/>
);
{this.state.success ? this.props.handler : null}
}
}
编辑:我纠正了拼写错误
答案 0 :(得分:0)
您的代码存在两个问题。第一个是拼写错误,第二个是你必须调用传递给子组件的回调函数。
export default class AppBar extends React.Component
{
constructor(props){
super(props);
this.state={RenderList: false}
this.handleRenderList=this.handleRenderList.bind(this);
}
handleRenderList()
{
this.setState({RenderList: true})
}
render()
{
return(
<div>
<AppBarLeft/>
<AppBarRight handler={this.handleRenderList}/> //Typo Error
{this.state.RenderList ? <MyList/> :null} //Typo Error
</div>
);
}
export default class AppBarRight extends React.Component
{
constuctor(props)
{
super(props);
this.state={success: false}
this.handleOnClick=this.handleOnClick.bind(this);
}
handleOnClick(){
getDetails(cred).then( (loginresp) => {
this.setState({ success: true} );
this.props.handler(); //Add this line for calling the callback function for changing the parent state.
}
}
...
render(){
return(
<Button onClick={this.handleOnClick}/> //Typo Error
);
{this.state.success ? this.props.handler : null}
}