鍍金池/ 問答/HTML/ 報錯:cannot read property 'style' of undef

報錯: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  表示組件的所有子節(jié)點
        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>阿達(dá)瓦得</div>

            </Screen>
        )
    }

    componentDidMount() {
        var varTest = 'test var OK';
        let letTest = 'test let OK'; // 綁定這個區(qū)域,不再受外部的影響
        {
            varTest = 'varTest change'
            let letTest = 'letTest change'
        }
        console.log(varTest);
        console.log(letTest);
    }
}



export default Component;
回答
編輯回答
獨特范
  1. children是一個數(shù)組,沒有props屬性
  2. {...this.props}相當(dāng)于是把這個對象分割開來,分別以屬性賦值給組件
2018年6月4日 00:01
編輯回答
澐染

1.不能直接修改this.props上的屬性,如果需要修改Screen 的子組件的樣式,應(yīng)該在Screen的父組件里修改
2.{...this.props}是es6的擴展運算符,假設(shè)

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

那么

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

相當(dāng)于

<Screen style={{ width: 1920, height: 1080 }} a={1} b={2}>
2017年5月30日 02:22