简体   繁体   中英

getDefaultProps with React Component Class

When i declared getDefaultProps function inside Class which is inherit from React.Component this give Error like Below

在此处输入图片说明

I setup condition in constructor for initialize props its 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"));

Thanks advance for help

After React's 0.13 release the props are required to be immutable. This being the case, getDefaultProps no longer makes sense as a function and should be refactored out to a property on the constructor, so

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

Try something like this:

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

The hint was in the error message, you need to use the static key word:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM