gpt4 book ai didi

javascript - 类型错误 : Cannot set property 'state' of undefined

转载 作者:行者123 更新时间:2023-12-02 19:06:47 28 4
gpt4 key购买 nike

我是 React JS 的初学者,我正在尝试学习如何使用状态并在 React 中使用状态,但我不断收到错误 无法设置未定义状态的属性

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;

最佳答案

如果您使用 class based react component,则上述设置状态的方法将会起作用。 .

但是您正在使用 functional component ,所以它不起作用。

这就是如何使用 React 函数组件和 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;

记住read the docs

Edit adoring-dew-3g7qc

关于javascript - 类型错误 : Cannot set property 'state' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64920087/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com