最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Cannot set property 'state' of undefined - Stack Overflow

programmeradmin6浏览0评论

I'm a beginner in React JS and I'm trying learn how to work with state and use state in react but I keep getting error cannot set property of state of undefined

import React from 'react';
import './App.css';
import './bootstrap.min.css';

function App() {
  this.state = {
    buttonColor: 'lightgreen'
  }
 
  const changeColor = () => {
    this.setState({buttonColor: this.state.buttonColor = 'lightblue'});
  }
  return (
    <button onClick={()=>changeColor()}  
            style={{ backgroundColor: this.state.buttonColor }} 
            className="btn text-white mt-5 ml-5">
      Change Color
    </button>
  );
}

export default App;

I'm a beginner in React JS and I'm trying learn how to work with state and use state in react but I keep getting error cannot set property of state of undefined

import React from 'react';
import './App.css';
import './bootstrap.min.css';

function App() {
  this.state = {
    buttonColor: 'lightgreen'
  }
 
  const changeColor = () => {
    this.setState({buttonColor: this.state.buttonColor = 'lightblue'});
  }
  return (
    <button onClick={()=>changeColor()}  
            style={{ backgroundColor: this.state.buttonColor }} 
            className="btn text-white mt-5 ml-5">
      Change Color
    </button>
  );
}

export default App;
Share Improve this question edited Dec 22, 2020 at 10:37 Software Engineer 16.1k8 gold badges84 silver badges107 bronze badges asked Nov 19, 2020 at 21:12 BlackDante101BlackDante101 912 silver badges9 bronze badges 2
  • 3 Are you trying to make a function ponent or a class ponent? Your issue is basically that you're mixing the syntaxes of them. – Nicholas Tower Commented Nov 19, 2020 at 21:14
  • reactjs/docs/hooks-state.html – Brian Thompson Commented Nov 19, 2020 at 21:14
Add a ment  | 

1 Answer 1

Reset to default 6

The above method of setting state would work if you were using a class based react ponent.

But you are using a functional ponent, so it does not work.

This is how you could do the same thing with a react function ponent and the useState hook.

import React, { useState } from "react";

function App() {
  const [buttonColor, setButtonColor] = useState("lightgreen");

  const changeColor = () => setButtonColor("lightblue");

  return (
    <button
      onClick={changeColor}
      style={{ backgroundColor: buttonColor }}
    >
      Change Color
    </button>
  );
}
export default App;

Remember to read the docs

发布评论

评论列表(0)

  1. 暂无评论