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>;


    }

调用

render() {

        return <PublicScreen style={{ width: 1920, height: 1080 }} {...this.props}>
                <div
                    className={'fl_screen'}>
                    {/* 应用资源使用量分析 */}
                    <Availability
                        styleSet={'cpu_availability'}
                        availability = {this.state.cpuAvailability}
                    />

                </div>

            </PublicScreen>;
    }

图片描述

阅读 13.2k
1 个回答

组件PublicScreen不支持style这个属性,如果要使用,必须在组件内定义这个属性。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题