我正在做一个React项目,在我的项目中我有两个按钮,对于第一个按钮,我为第二个按钮分配了一个状态,我写了一个函数,我也分配了一个状态。但是我的onClick函数不起作用。请帮我解决这个问题。
这是App.js
import React, { useState } from "react";
import { Button } from "antd"
import 'antd/dist/antd.css';
import "./App.css";
const App = () => {
const [buttonOne, setButtonOne] = useState("red")
const [buttonTwo, setButtonTwo] = useState("blue")
const buttonTwoBackgroundColor = () => {
setButtonTwo({
backgroundColor: "red",
border: "red"
})
}
return (
<div>
<Button style={{backgroundColor: buttonOne, border: buttonOne}} className="one" type="primary">First</Button>
<Button style={{backgroundColor: buttonTwo, border: buttonTwo}} onClick={buttonTwoBackgroundColor} className="two" type="primary">Second</Button>
</div>
)
}
export default App
这是App.css
.one {
margin-right: 5px;
margin-left: 250px;
margin-top: 50px;
}
.two, .three, .four, .five {
margin-right: 5px;
}
发布于 2021-07-16 19:06:58
在function buttonTwoBackgroundColor中,可以将setButtonTwo设置为对象。它应该是一个字符串。
const buttonTwoBackgroundColor = () => {
setButtonTwo("red")
}
发布于 2021-07-16 19:07:40
当您将默认状态定义为字符串时,您正在尝试将state设置为对象。
将默认状态更新为对象,然后像这样访问属性:
import React, { useState } from "react";
import { Button } from "antd";
import "./styles.css";
export default function App() {
const [buttonOne, setButtonOne] = useState("red");
const [buttonTwo, setButtonTwo] = useState({backgroundColor: "blue", border: "blue"});
const buttonTwoBackgroundColor = () => {
setButtonTwo(prevState => ({
...prevState,
backgroundColor: 'blue',
border: 'red'
}));
};
return (
<div>
<Button
style={{ backgroundColor: buttonOne, border: buttonOne }}
className="one"
type="primary"
>
First
</Button>
<Button
style={{ backgroundColor: buttonTwo.backgroundColor, border: buttonTwo.border }}
onClick={buttonTwoBackgroundColor}
className="two"
type="primary"
>
Second
</Button>
</div>
);
}
发布于 2021-07-16 19:08:13
变化
onClick={buttonTwoBackgroundColor}
至
onClick={setButtonTwo("red")}
您在初始化时使用useState作为字符串,并在下面的函数中分配对象,这是不正确的方式!
https://stackoverflow.com/questions/68407888
复制相似问题