Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - react fails to inline change the background color of a button

I am trying to inline toggle the background color of the submit button with react and state. I am aware that this can be achieved through a bool value isMouseOver ? "black" : "white" in style. But I wonder why my first attempt does not work? Even though the variable myColor has been changed by my mouse action:

    import React, { useState } from "react";

    function App() {
      const [myColor, setColor] = useState("white");
    
    
    
      function toggleColor() {
        if (myColor === "black") {
          setColor("white");
        } else {
          setColor("black");
        }
        console.log("mycolor", myColor);
      }
    
      return (
        <div className="container">
          <h1>{myColor}</h1>
          <input type="text" placeholder="What's your name?" />
          <button
            style={{ backgroundColor: { myColor } }}
            onMouseOver={toggleColor}
            onMouseOut={toggleColor}
          >
            Submit
          </button>
        </div>
      );
    }
    
    export default App;


question from:https://stackoverflow.com/questions/65598823/react-fails-to-inline-change-the-background-color-of-a-button

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

just change this line i.e remove the curly braces around myColor, it should working fine

 style={{ backgroundColor: { myColor } }} 

to

 style={{ backgroundColor:  myColor  }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...