简体   繁体   中英

Why does it say uncaught Reference error: counter is not defined?

I'm practicing how to create components that have a state with reactJS unfortunately I can't figure out what is wrong. I have mirrored this from a previous example and there is literally no difference aside from the reandomNumber function in which I generate a new number each time I click the button. If anybody can give me feedback on what I did wrong I would appreciate it. Also, there is nothing showing within my UI window.

var Count = React.createClass({
    render: function() {
        var counterStyle = {
            fontSize: 20,
            fontFamily: "times",
            padding: 50,
            color: "blue"
        };

        return(
            <p style="counterStyle">{this.props.display}</p>
        );
    }
});


var ButtonButton = React.createClass({
    render: function() {
        var buttonStyle = {
            fontSize: "1em",
            width: 60,
            height: 40,
            fontFamily: "times",
            color: "teal",
            fontWeight: "bold",
            lineHeight: "3px"
        };

        return(
            <button style={buttonStyle} onClick={this.props.eventHandle}>Random No.</button>
       );
    }
});

var ButtonSquare = React.createClass({
    getInitialState: function() {
        return(
            counter: 0
        );
    },

    randomNumber: function() {
        this.setState({
            counter: Math.floor(Math.random())
        });
    },


    render: function() {
        var linkStyle = {
            width: 900,
            height: 900,
            backgroundColor: "blue",
            textAlign: "center"
        };


        return (
            <div style={linkStyle}>
                <Count display={this.state.counter}/>
                <ButtonButton eventHandle={this.randomNumber}/>
            </div>
        );
    }
});

You've used the wrong punctuation here and accidently made a labelled statement for 0 instead of an object with a property:

getInitialState: function() {
    return(
        counter: 0
    );
},

This should be

getInitialState: function() {
    return {
        counter: 0
    };
},

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