admin管理员组文章数量:1328621
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
1 Answer
Reset to default 6The 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
本文标签: javascriptTypeError Cannot set property 39state39 of undefinedStack Overflow
版权声明:本文标题:javascript - TypeError: Cannot set property 'state' of undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742232764a2437523.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论