0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React setStateでstyle切り替え

Posted at

全体

App.js
import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      <Func2/>
    </div>
  );
}

const Func2 = () => {
  const [bool,setBool] = useState(false);
  const status1 = {
    color:'blue'
  }

  const status2 = {
    color:'green'
  }

  return (
    <div>
      <h1 style={bool ? status1 : status2}>Hello</h1>
      <button onClick={()=> setBool(!bool)}>button</button>
    </div>
  );
}

export default App;

つくったやつ

const Func2 = () => {
  const [bool,setBool] = useState(false);
  const status1 = {
    color:'blue'
  }

  const status2 = {
    color:'green'
  }

  return (
    <div>
      <h1 style={bool ? status1 : status2}>Hello</h1>
      <button onClick={()=> setBool(!bool)}>button</button>
    </div>
  );

ステート変数boolが変更されると再レンダリングされる
ボタンを押すとboolが変更されて色が変わる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?