如何在react中为状态分配props值

IT技术 reactjs babeljs
2021-05-17 15:28:26

我有一个从另一个 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 值并将其分配给状态,但它不起作用。如何将 prop 值分配给 state 并使用它?

问候, JP

4个回答

您在 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>
       );
    }
}

完整的工作示例:https : //codesandbox.io/s/35wLR4nA

constructor(props, context) {
    super(props, context);
     this.state = {
           value: ''
      };
   }

   componentWillReceiveProps(){ //this is called to before render method
    this.setState({
       value:this.props.data
     })

您的问题可能是您正在尝试使用this. 我认为您应该使用传递给构造函数的props。

像这样:

constructor (props){
    super(props);
    this.state = {open: false}
    this.setState({ open: props.isOpen });
}

不知道为什么你没有像这样在一行中做到这一点: this.setState = { open: props.isOpen };

最后我保留了改变类的属性,这样也不错。我在这个帮助下修复了:将props传递给 React.js 中的父组件,当然还有同事的帮助。最终版本是这样的:

这是家长:

export default class StatusBarButtonView_Profit extends React.Component {

    constructor(props) {
        super(props)
        this.state = {active: false}
        this._openOverlay = this._openOverlay.bind(this)
        this._closeOverlay = this._closeOverlay.bind(this)
    }

    _openOverlay() {
        if (this.state.active == false) {
            this.setState({ active: true });
            console.log('boton lanza overlay');
        } else {
            this.setState({ active: false });
            console.log('boton cierra overlay');
        }
    }

    _closeOverlay(Overlay) {
        if (this.state.active == true) {
            this.setState({ active: false });

        } else {
            this.setState({ active: true });
        }
    }

    render() {
        var cx = require('classnames');
        var button = cx ({
            'aui-profit-statusbar-button-container' : true,
            'active' : this.state.active
        });
        var animation = cx ({
            'aui-profit-statusbar-button-cross-image' : true,
            'rotate' : true,
            'active' : this.state.active
        });

        return (
            <div className="aui-profif-statusbar-center-wrapper">
                <div className={button} onClick={this._openOverlay}>
                    <img src="images/aui-navbar-element-icon-cross.png" className={animation}/>
                </div>      
                <OverlayView_Profit isOpen={this.state.active} onClick={this._closeOverlay}/>
            </div>
        );
    }
}

这是孩子:

export default class OverlayView_Profit extends React.Component {
    constructor (props){
        super(props);

    }

    _closeOverlay() {
        this.props.onClick();
    }

    render() {
        var cx = require('classnames');
        var overlay = cx({
            'aui-overlay': true,
            'aui-overlay-slidedown': true,
            'open': this.props.isOpen
        });

        return (    
            <div className={overlay} onClick={this._closeOverlay.bind(this)}>
                <OverlayNewInvoiceButtonView_Profit />
                <OverlayNewBudgetButtonView_Profit />
                <OverlayNewTicketButtonView_Profit />
            </div>
        );
    }
}

现在一切正常。