我真的很陌生。我试图让父母根据状态更改显示的页面。我的子组件中有一个按钮,应该向父组件发送“ true”或“ false”,以便它知道是否进行渲染。我认为应该用这样的道具来完成:
this.state = {
btnNewScreen: this.props.btnNewScreen //true or false
};
但我无法使其正常工作。你能给点建议吗?这是完整的父母-子女
父-maindisplay.js
import React from 'react';
import Mainpage_Addscreen from '../components/subcomponents/mainpage-addscreen';
import Mainpage_Showscreens from '../components/subcomponents/mainpage-showscreens';
//
class MainDisplay extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: false //should be this.props.btnNewScreen?
};
}
render() {
var renderThis;
if (!this.state.btnNewScreen) {
renderThis =
<div>
<Mainpage_Addscreen />
<Mainpage_Showscreens />
</div>
}
else {
//renderThis = <AddScreen />
renderThis =
<div>
<Mainpage_Addscreen />
<h3>Change to this when true (button click)</h3>
</div>
}
return (
<div>
{renderThis}
</div>
);
}
}
export default MainDisplay;
child-mainpage-addscreen.js
import React from 'react';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Button from 'react-bootstrap/lib/Button';
class Mainpage_Addscreen extends React.Component {
constructor() {
super();
this.state = {
btnNewScreen: true
};
this.newScreen = this.newScreen.bind(this);
}
newScreen(e) {
this.setState({ btnNewScreen: !this.state.btnNewScreen });
console.log(this.state.btnNewScreen);
}
render() {
var text = this.state.btnNewScreen ? 'Add new' : 'Screens';
return (
<div className="main_window col-sm-offset-1 col-sm-10">
<h3 id="addscreens">Screens: </h3>
<Button id="addScreen" className="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" onClick={this.newScreen}><Glyphicon id="refresh_screens" glyph="plus" /> {text}</Button>
</div>
);
}
}
export default Mainpage_Addscreen;
您需要做的是将方法从父级传递给子级,单击该按钮时可以调用该方法。属于父级的此方法将更改状态。在MainPage.js中
changeButtonState(event) {
this.setState({btnNewScreen: !this.state.btnNewScreen})
}
将此方法作为]传递给您的子组件>
<Mainpage_Addscreen buttonClick={this.changeButtonState.bind(this)} />
最后是子组件,
<Button .... onClick={this.props.buttonClick} />
您可能需要一个回调函数,父母将其作为道具传递给孩子,然后孩子可以呼叫。