带有React组件类的getDefaultProps

时间:2016-08-28 04:40:11

标签: javascript reactjs ecmascript-6 babeljs

当我在继承自getDefaultProps的Class中声明React.Component函数时,这会给出类似下面的错误

enter image description here

我在构造函数中设置条件,以初始化props undefined

import React from "react"
import ReactDOM from "react-dom"

class App extends React.Component{
    propTypes:{
        techstack : React.PropTypes.string
    }

    constructor(){
        super();
        this.props.techstack === undefined ? "Rails" : ''
        console.log(this.props);
    }

    render(){
        return (<div>
                 <h2>{this.props.techstack} Rocks</h2>
                </div>
               )
    }
}

ReactDOM.render(<App/>,document.getElementById("app"));

感谢提前寻求帮助

3 个答案:

答案 0 :(得分:2)

在React的0.13版本发布后,props必须是不可变的。在这种情况下,getDefaultProps作为一个函数不再有意义,应该重构为构造函数的属性,所以

import React from "react"
import ReactDOM from "react-dom"

class App extends React.Component{
    propTypes:{
        techstack : React.PropTypes.string
    }

    constructor(){
        super();
        this.props.techstack === undefined ? "Rails" : ''
        console.log(this.props);
    }

    render(){
        return (<div>
                 <h2>{this.props.techstack} Rocks</h2>
                </div>
               )
    }
}
    App.defaultProps = {key: 'value'};

ReactDOM.render(<App/>,document.getElementById("app"));

答案 1 :(得分:1)

尝试这样的事情:

import React from "react"
import ReactDOM from "react-dom"

class App extends React.Component{
    propTypes:{
        techstack : React.PropTypes.string
    }

    constructor(){
        super();
        this.props.techstack === undefined ? "Rails" : ''
        console.log(this.props);
    }

    render(){
        return (<div>
                 <h2>{this.props.techstack} Rocks</h2>
                </div>
               )
    }
}

App.defaultProps = { prop: 'value' };

ReactDOM.render(<App/>,document.getElementById("app"));

答案 2 :(得分:1)

提示在错误消息中,您需要使用静态关键字:

import React from "react"
import ReactDOM from "react-dom"

class App extends React.Component{

    static propTypes:{
        techstack : React.PropTypes.string
    }

    static defaultProps: {
        techstack: 'Rails'
    }

    constructor(props){
        super(props);
        console.log(props);
    }

    render(){
        return (<div>
                 <h2>{this.props.techstack} Rocks</h2>
                </div>
               )
    }
}

ReactDOM.render(<App/>,document.getElementById("app"));