如何使用钩子在反应中将状态定义为对象

问题描述

我正在处理一个 React 项目,我正在尝试为按钮定义一个状态。但是状态不适用于按钮,请您纠正我

这是我的代码

这是 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({
    backgroundColor: "red",color: "black",border: "red"
  })


  return (
    <div>
      <Button style={{backgroundColor: buttonOne,border: buttonOne}} className="one" type="primary">First</Button>
      <Button style={{backgroundColor: buttonTwo,color: buttonTwo,border: buttonTwo}} className="two" type="primary">Second</Button>
    </div>
  )
}

export default App
````

解决方法

试试这个

<div>
   <Button style={{backgroundColor: buttonOne,border: buttonOne}} className="one" type="primary">First</Button>
   <Button style={{backgroundColor: buttonTwo.backgroundColor,color: buttonTwo.color,border: buttonTwo.border}} className="two" type="primary">Second</Button>
</div>

由于您的状态是对象,您需要进入内部字段,例如 -

buttonTwo.borderbuttonTwo['color']

示例

<Button style={{backgroundColor: buttonTwo.backgroundColor,color: buttonTwo['color'],border: buttonTwo.border}} className="two" type="primary">Second</Button>
,

对于第二个按钮,您需要访问对象的属性。

backgroundColor: buttonTwo.backgroundColor

color: buttonTwo.color

border: buttonTwo.border

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...