鍍金池/ 問答/HTML/ React項目Cannot add property style, object

React項目Cannot add property style, object is not extensible

import React from 'react';


class PublicScreen extends React.Component {
    constructor(props) {
        super(props);

        this.getStyle = this.getStyle.bind(this);
    }


    getStyle() {
        const { width = 1920, height = 1080 } = this.props.style || {};

        const root = document.querySelector('#root');
        const per = root.clientWidth / width;
        return {
            width: width,
            height: height,
            transformOrigin: 'left top',
            transform: 'scale(' + per + ')'
        };
    }


    render() {

        const { width = 1920, height = 1080 } = this.props.style || {};

        const childrenStyle = this.props.children.props.style || {};
        this.props.children.props.style = { height, width, ...childrenStyle };

        return <div ref={(elem) => { this.element = elem; }}
                    className="screen">
            {this.props.children}
        </div>;


    }

    componentDidMount() {


        // 分辨率適配縮放
        const screen = this.element;
        const getStyle = this.getStyle;

        function adaptiveScreen() {
            const style = getStyle();
            for (let k in style) {
                screen.style[k] = style[k];
            }
        }

        let timeout = null;
        window.addEventListener('resize', () => {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                adaptiveScreen();
            }, 400);
        });
        adaptiveScreen();


    }


}

export default PublicScreen;

補充

PublicScreen組件

render() {

        const { width = 1920, height = 1080 } = this.props.style || {};

        const childrenStyle = this.props.children.props.style || {};
        this.props.children.props.style = { height, width, ...childrenStyle };

        return <div ref={(elem) => { this.element = elem; }}
                    className="screen">
            {this.props.children}
        </div>;


    }

調(diào)用

render() {

        return <PublicScreen style={{ width: 1920, height: 1080 }} {...this.props}>
                <div
                    className={'fl_screen'}>
                    {/* 應(yīng)用資源使用量分析 */}
                    <Availability
                        styleSet={'cpu_availability'}
                        availability = {this.state.cpuAvailability}
                    />

                </div>

            </PublicScreen>;
    }

圖片描述

回答
編輯回答
墨沫

組件PublicScreen不支持style這個屬性,如果要使用,必須在組件內(nèi)定義這個屬性。

2018年2月11日 20:25