我真的很反应。我正在尝试让父母根据状态更改显示的页面。我的子组件中有一个按钮,它应该向父组件发送“true”或“false”,以便它知道是否要呈现它。我认为应该用这样的道具来完成:
this.state = {
btnNewScreen: this.props.btnNewScreen //true or false
};
但是我没有让它发挥作用。你能给出任何提示吗?这是完整的父母 - 孩子
parent - 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;
答案 0 :(得分:18)
您需要做的是将方法从父级传递给子级,单击该按钮时可以调用该方法。属于父级的此方法将更改状态 在MainPage.js
changeButtonState(event) {
this.setState({btnNewScreen: !this.state.btnNewScreen})
}
将此方法传递给您的子组件,作为
<Mainpage_Addscreen buttonClick={this.changeButtonState.bind(this)} />
最后在子组件中,
<Button .... onClick={this.props.buttonClick} />
答案 1 :(得分:3)
您可能需要的是一个回调函数,您的父母将其作为道具传递给您的孩子,然后您的孩子可以打电话。
这样的事情:
// In parent
constructor() {
...
this.onChildClicked = this.onChildClicked.bind(this);
}
onChildClicked() {
this.setState({childWasClicked : True });
}
render() {
...
return (
<div>
<Child onClicked={this.onChildClicked} />
</div>
)
}
// In child
render() {
...
return (
<div>
<button onClick={this.props.onClicked} />
</div>
)
}
PS:我注意到你有一个大写的<Button>
组件。这通常适用于您自己定义的组件。标准DOM元素采用小写,例如<div>
,<p>
等