20201011 TIL useState

14578 ワード

React Functional Component


useState? (feat. accordion)


従来stateはclassコンポーネントでしか使用できなかったがfunctionalコンポーネントで使用する方法もある.USStateを利用することです!
import React, { useState } from 'react';

const Accordion = ({ items }) => {
    const [activeIndex, seetActiveIndex] = useState(null);
    const onTitleClick = (index) => {
        seetActiveIndex(index);
    }
    const renderedItems = items.map((item, index) => {
        const active = index === activeIndex ? 'active' : '';
        return (
            <React.Fragment key={item.title}>
                <div
                    onClick={() => onTitleClick(index)}
                    className={`title ${active}`}>
                    <i className="dropdown icon"></i>
                    {item.title}
                </div>
                <div className={`content ${active}`}>
                    <p>{item.content}</p>
                </div>
            </React.Fragment>
        )
    });
    return (
        <div className="ui styled accordion">
            {renderedItems}
        </div>);
}

export default Accordion;
上記のコードでは、userStateを使用してstateを設定できます.
ActiveIndexをステータス名、setActiveIndexをsetState名として使用します.

上の画像を見るとよく理解できます!:D
useStateを使うとfunctional componentでもstateを使うことができますが、素敵に見えますが...隠れた小さな欠点がある.つまり、setStateのように一度に複数のstateを変更することはできません.
// classComponent
class App extends React.Component {
  state={color:"red",content:"red color"};
  handleButton = () => {
    this.setState({color:"green",content:"green"});
  }
  render(){
    return (
      <div>
     	 <h1 style={{color: this.state.color}}}>{this.state.content}</h1>
     	 <button onClick={this.handleButton}>Change Color</button>
      </div>
  }
};

// functionaComponent
const App = () => {
    const [color, setColor] = useState("red");
    const [content, setContent] = useState("red color");
    const buttonHandler = () => {
        setColor("green");
        setContent("green color");
    }
    return (
        <div>
            <h1 style={{ color: color }}>{content}</h1>
            <button onClick={() => buttonHandler()}>Change Color</button>
        </div>
    )
}
useStateと似ているのはuseEffect、useRefなどで、これらの友人を総称してReactionのHooksと呼ぶ.:)