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

时间:2021-07-16 13:18:45

标签: reactjs

我正在处理一个 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
````

2 个答案:

答案 0 :(得分:1)

试试这个

<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>

答案 1 :(得分:1)

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

backgroundColor: buttonTwo.backgroundColor

color: buttonTwo.color

border: buttonTwo.border