报错:cannot read property 'style' of undefined

问题一

报错

图片描述

问题二

{...this.props} 这个是什么意思

 <Screen style={{ width: 1920, height: 1080 }} {...this.props}>

源码

import React from 'react';

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

    render() {


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

        // this.props.children  表示组件的所有子节点
        const childrenStyle = this.props.children.props.style || {};
        this.props.children.props.style = { height, width, ...childrenStyle };

        return (
            <div className={'screen'}>
                {this.props.children}
            </div>
        )

    }
}

export default Screen;
import React from 'react';
import Screen from './components/screen';

import './assets/styles';


class Component extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mapPoint: [],
            area: [],
            bar: []
        };
    }

    render() {

        return (
            <Screen style={{ width: 1920, height: 1080 }} {...this.props}>
                <div>思考思考</div>
                <div>瞬间即逝</div>
                <div>阿达瓦得</div>

            </Screen>
        )
    }

    componentDidMount() {
        var varTest = 'test var OK';
        let letTest = 'test let OK'; // 绑定这个区域,不再受外部的影响
        {
            varTest = 'varTest change'
            let letTest = 'letTest change'
        }
        console.log(varTest);
        console.log(letTest);
    }
}



export default Component;
阅读 4.2k
2 个回答
  1. children是一个数组,没有props属性
  2. {...this.props}相当于是把这个对象分割开来,分别以属性赋值给组件

1.不能直接修改this.props上的属性,如果需要修改Screen 的子组件的样式,应该在Screen的父组件里修改
2.{...this.props}是es6的扩展运算符,假设

this.props = {
    a: 1,
    b: 2,
}

那么

<Screen style={{ width: 1920, height: 1080 }} {...this.props}>

相当于

<Screen style={{ width: 1920, height: 1080 }} a={1} b={2}>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题