【问题标题】:How to assign a prop value to a state in react如何在反应中将道具值分配给状态
【发布时间】:2015-07-16 12:52:11
【问题描述】:

我有一个覆盖层,它是从另一个 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 值分配给 state 并使用它?

问候, JP

【问题讨论】:

  • 我试过用户 WayneC 说,this.state = {open: this.props.isOpen} 并且它不起作用。

标签: reactjs babeljs


【解决方案1】:
constructor(props, context) {
    super(props, context);
     this.state = {
           value: ''
      };
   }

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

【讨论】:

  • componentWillReceiveProps 现已弃用!!
  • 对构造函数本身使用 UNSAFE_ComponentWillReceiveProps 或赋值。
【解决方案2】:

您的 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

【讨论】:

  • 现已弃用
【解决方案3】:

最后我保存了更改类的属性,这样还不错。我在这个帮助下修复了:Pass props to parent component in 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>
        );
    }
}

现在一切正常。

【讨论】:

    【解决方案4】:

    您的问题可能是您尝试使用this 获取类道具。我认为您应该使用传递给构造函数的道具。

    像这样:

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

    不知道你为什么不这样做:this.setState = { open: props.isOpen };

    【讨论】:

    • 感谢您的帮助,但它不适用于您提到的任何方式。
    • 属性是传递给子组件还是在此之前停止?
    • 道具被传递给子组件,在这样做之前我在类名中做了类似'open': this.props.isOpen的事情,它工作正常,但我必须改变它。
    • Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ... component
    猜你喜欢
    • 2019-11-16
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多