未定义的参考错误:状态未定义(react.js)

发布于 2025-02-06 01:37:48 字数 3516 浏览 1 评论 0原文

这里的初学者。这个错误不断弹出,我不知道原因。我的网页确实显示了我对脚本进行的更改,但是只有当我评论样式隐藏形状或保持形状以显示形状时,我的网页才会进行更改。

我想创建一个网页,每秒钟都会通过其大小,边框半径(“百分比”)和背景颜色更改形状的外观。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue; 
            border-radius: 50%;  
        }   
    </style>
</head>
<body>
    <div class="shape-item">
        <div></div>
        <div></div>
    </div>

    <script type="text/babel">

        "use strict";

        var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];
        
        class Shapes extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: 100,
                        perCent: "%50"
                    }
                }
            }

            componentDidMount(){
                this.timerID = setInterval(() => this.updateShape(), 1000);
            }

            componentWillUnmount(){
                clearInterval(this.timerID);
            }

            updateShape(){
                let randomIndex = Math.floor((Math.random() * colours.length));
                this.setState(
                    {
                        shape: {
                            bgColour: colours[Math.floor((Math.random() * colours.length))],
                            size: (Math.random() * 125),
                            perCent: (Math.random() * 100)
                        }
                    }
                )
            }

            render(){
                var shapeStyle = {
                    padding: 10,
                    margin: 20,
                    display: 'inline-block',
                    backgroundColor: {this:state.bgColour},
                    borderRadius: {this:state.perCent},
                    width: {this:state.size},
                    height: {this:state.size}
                }
                return(
                    <div style={shapeStyle}>
                        {this.state.shape}
                    </div>
                )
            }
        }

        ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

        shapesRender = [];

        for(let i=0; i < 60; i++){
            shapesRender.push(<Shapes key={i} />);
        }

        ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

    </script>
</body>
</html>

Beginner here. This error keeps popping up, and I can't figure out why. My webpage does show changes that I make to the script, but only when I comment out the style to hide the shape, or keep it in to show a shape.

I'm wanting to create a webpage that, every second, changes the appearance of the shape by its size, border radius ('perCent'), and the background colour.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue; 
            border-radius: 50%;  
        }   
    </style>
</head>
<body>
    <div class="shape-item">
        <div></div>
        <div></div>
    </div>

    <script type="text/babel">

        "use strict";

        var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];
        
        class Shapes extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: 100,
                        perCent: "%50"
                    }
                }
            }

            componentDidMount(){
                this.timerID = setInterval(() => this.updateShape(), 1000);
            }

            componentWillUnmount(){
                clearInterval(this.timerID);
            }

            updateShape(){
                let randomIndex = Math.floor((Math.random() * colours.length));
                this.setState(
                    {
                        shape: {
                            bgColour: colours[Math.floor((Math.random() * colours.length))],
                            size: (Math.random() * 125),
                            perCent: (Math.random() * 100)
                        }
                    }
                )
            }

            render(){
                var shapeStyle = {
                    padding: 10,
                    margin: 20,
                    display: 'inline-block',
                    backgroundColor: {this:state.bgColour},
                    borderRadius: {this:state.perCent},
                    width: {this:state.size},
                    height: {this:state.size}
                }
                return(
                    <div style={shapeStyle}>
                        {this.state.shape}
                    </div>
                )
            }
        }

        ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

        shapesRender = [];

        for(let i=0; i < 60; i++){
            shapesRender.push(<Shapes key={i} />);
        }

        ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

    </script>
</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倦话 2025-02-13 01:37:50

您正在使用colons访问状态 的属性。它应该是一个点。而且,由于您正在构建用于内联样式的常规JS对象,因此您无需将每个键的值放入嵌套的JS对象中,就像您为背景颜色,Borderradius,宽度和高度所做的那样。它应该看起来像这样:

var shapeStyle = {
  padding: 10,
  margin: 20,
  display: 'inline-block',
  backgroundColor: this.state.bgColour,
  borderRadius: `${this.state.perCent}%`, // append % to numerical perCent value
  width: this.state.size,
  height: this.state.size
}

附加说明,您为百分比提供的初始值是“%50”,它是字符串,具有百分比符号,并且在正面,但是每个更新,将其更改为新的数字值。我会将其保留为一个数字(将初始值从百分比更改为“%50” 百分比:50 ),然后在最后一个中添加百分比符号在将它们全部插入样式对象的位置,就像我上面一样。

并指出尼克的观点(在帖子的评论中),如果要在DIV中显示状态对象,以便您可以看到样式如何受到影响,但是您需要使用json.stringify (this.state.shape)。如果您打算以外的其他JS对象显示其他内容,则需要进行调整,以便您显示新的组件或HTML元素,而不仅仅是字符串。

You are using colons to access the state property of this. It should be a dot. And since you are constructing a regular JS object to use for inline styles, you don't need to put the values of each key into a nested JS object, like you're doing for backgroundColor, borderRadius, width, and height. It should look like this:

var shapeStyle = {
  padding: 10,
  margin: 20,
  display: 'inline-block',
  backgroundColor: this.state.bgColour,
  borderRadius: `${this.state.perCent}%`, // append % to numerical perCent value
  width: this.state.size,
  height: this.state.size
}

An additional note, the initial value you are providing for perCent is "%50", which is a string and has a percent symbol and has it at the front, but every update, it is changed to a new Number value. I would keep it as a number from the get go (change the initial value from perCent: "%50" to perCent: 50) and add the percent sign in the last step where you interpolate it all into a styles object, like I did above.

And to Nick's point (in the comments on the post), if you want to display the state object in the div so you can see how the styles are affected, that's fine, but you'll need to use JSON.stringify(this.state.shape). If you are intending for something else to display than the actual JS object, you'll need to make adjustments so you are displaying a new component or HTML element rather than just a string.

岁月静好 2025-02-13 01:37:50

未定义状态是因为您使用了错误的语法“:”

使用{this.state.shape.bgcolour} for {this:state.bgcolour}

您无法在jsx中使用{}的对象显示一个对象:

thise {this。 state.shape} to {this.state.shape.size}
更改{this:state.bgcolour} {this.state.shape.bgcolour} ...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<div class="shape-item">
    <div></div>
    <div></div>
</div>

<script type="text/babel">

    "use strict";

    var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];

    class Shapes extends React.Component{

        constructor(props){
            super(props);
            this.state = {
                shape: {
                    bgColour: colours[Math.floor((Math.random() * colours.length))],
                    size: 100,
                    perCent: "%50"
                }
            }
        }

        componentDidMount(){
            this.timerID = setInterval(() => this.updateShape(), 1000);
        }

        componentWillUnmount(){
            clearInterval(this.timerID);
        }

        updateShape(){
            let randomIndex = Math.floor((Math.random() * colours.length));
            this.setState(
                {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: (Math.random() * 125),
                        perCent: (Math.random() * 100)
                    }
                }
            )
        }

        render(){
            console.log(this.state)
            var shapeStyle = {
                padding: 10,
                margin: 20,
                display: 'inline-block',
                backgroundColor: this.state.shape.bgColour,
                borderRadius: this.state.shape.perCent,
                width: this.state.shape.size,
                height: this.state.shape.size
            }
            return(
                <div style={shapeStyle}>
                    {this.state.shape.size}
                </div>
            )
        }
    }

    ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

    let shapesRender = [];

    for(let i=0; i < 60; i++){
        shapesRender.push(<Shapes key={i} />);
    }

    ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

</script>
</body>
</html>

State is not defined because you used the wrong syntax ":"

Use {this.state.shape.bgColour} for {this:state.bgColour}

You can not show a object with {} in jsx:

Change {this.state.shape} to {this.state.shape.size}
Change {this:state.bgColour} to {this.state.shape.bgColour} ...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<div class="shape-item">
    <div></div>
    <div></div>
</div>

<script type="text/babel">

    "use strict";

    var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];

    class Shapes extends React.Component{

        constructor(props){
            super(props);
            this.state = {
                shape: {
                    bgColour: colours[Math.floor((Math.random() * colours.length))],
                    size: 100,
                    perCent: "%50"
                }
            }
        }

        componentDidMount(){
            this.timerID = setInterval(() => this.updateShape(), 1000);
        }

        componentWillUnmount(){
            clearInterval(this.timerID);
        }

        updateShape(){
            let randomIndex = Math.floor((Math.random() * colours.length));
            this.setState(
                {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: (Math.random() * 125),
                        perCent: (Math.random() * 100)
                    }
                }
            )
        }

        render(){
            console.log(this.state)
            var shapeStyle = {
                padding: 10,
                margin: 20,
                display: 'inline-block',
                backgroundColor: this.state.shape.bgColour,
                borderRadius: this.state.shape.perCent,
                width: this.state.shape.size,
                height: this.state.shape.size
            }
            return(
                <div style={shapeStyle}>
                    {this.state.shape.size}
                </div>
            )
        }
    }

    ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

    let shapesRender = [];

    for(let i=0; i < 60; i++){
        shapesRender.push(<Shapes key={i} />);
    }

    ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

</script>
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文