我有一个从另一个React组件启动的叠加层,它有一个也会自行更改的按钮.当用户单击按钮时,会发生更改,然后按钮会更改其类名.它还向作为叠加层的子组件发送prop值.叠加层根据属性添加
那么这是按钮组件:
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> ); } }
而这就是目前的叠加:
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> ); } }
如你所见,我试图获得道具价值并将其分配给州,但它不起作用.如何将prop值分配给状态并使用它?
问候,
J.P
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> ); } }
完整的工作示例:
https://codesandbox.io/s/35wLR4nA