我有一个从另一个React组件启动的叠加层,它有一个也会自行更改的按钮.当用户单击按钮时,会发生更改,然后按钮会更改其类名.它还向作为叠加层的子组件发送prop值.叠加层根据属性添加一个类,如果单击它.Everthing工作得很好,但现在我必须做另外一件事.当用户点击叠加层时,它必须关闭.在此更改之前,所有内容都适用于我之前提到的按钮.
那么这是按钮组件:
export default class StatusBarButton extends React.Component {
constructor(props) {
super(props)
this.state = {active: false}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ active: !this.state.active });
}
render() {
var cx = require('classnames');
var button = cx ({
'statusbar-button-container' : true,
'active' : this.state.active
});
var animation = cx ({
'statusbar-button-cross-image' : true,
'rotate' : true,
'active' : this.state.active
});
return (
<div className="astatusbar-center-wrapper">
<div className={button} onClick={this.handleClick}>
<img src="images/navbar-element-icon-cross.png" className={animation}/>
</div>
<OverlayView isOpen={this.state.active} />
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
而这就是目前的叠加:
export default class OverlayView extends React.Component {
constructor (props){
super(props);
this.state = {open: false}
this.setState({ open: this.props.isOpen });
}
render() {
var cx = require('classnames');
var overlay = cx({
'overlay': true,
'overlay-slidedown': true,
'open': this.state.open
});
return (
<div className={overlay} onClick={this._closeOverlay}>
<div className="overlay-menu-wrapper">
<OverlayNewInvoiceButton />
<OverlayNewBudgetButton />
<OverlayNewTicketButton />
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我试图获得道具价值并将其分配给州,但它不起作用.如何将prop值分配给状态并使用它?
此致,JP
小智 8
您缺少OverlayView组件中的componentWillReceiveProps(props)方法.
export default class OverlayView extends React.Component {
constructor (props){
super(props);
this.state = {open: props.isOpen}
}
componentWillReceiveProps(props) {
this.setState({open: props.isOpen});
}
render() {
let open = '';
if (this.state.open === true) {
open = 'open';
}
let overlayClass = `overlay overlay-slidedown ${open}`;
return (
<div className={overlayClass} onClick={this._closeOverlay}>
<div className="overlay-menu-wrapper">
<span>{open}</span>
</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
完整的工作示例:https: //codesandbox.io/s/35wLR4nA
您的问题可能是您正在尝试使用 来获取类道具this。我认为你应该使用传递给构造函数的道具。
像这样:
constructor (props){
super(props);
this.state = {open: false}
this.setState({ open: props.isOpen });
}
Run Code Online (Sandbox Code Playgroud)
不知道为什么你不这样做在一行像这样:this.setState = { open: props.isOpen };
| 归档时间: |
|
| 查看次数: |
15787 次 |
| 最近记录: |