React.jsをYoutube動画で学ぶ③~props、state、useState、import、export~

www.youtube.com

www.youtube.com

 

[props + state  のサンプルコード]

title属性でテキストの文字列を設定し、buttonText属性で、ボタンに表示される文字列を設定し、そのボタンを押すと、テキストの文字列が置き換わるような、テキストとボタンがセットになったタグ<Btc>を作る。(この際、タグ名の初めは必ず大文字でないとエラーになります)

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import ButtonText from './ButtonText'
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ButtonText />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

ButtonText.js

import './buttontext.css';
import Btc from './components/BTContents';

const ButtonText = ()=>{
   return(
    <div className='text'>
        <Btc
            text = {"今日は休み"}
            buttonText = {"PUSH"}
        />
    </div>
   )
}

export default ButtonText;

BTContents.js

import { useState } from "react";

const Btc = function(props){
    const [description,setDescription] = useState('今日は休み');
    function changeDescription(){
        setDescription('今日は仕事');
    }
    return(
        <div>
          <div>{props.text}</div>
          <div>
            {description}
          </div>
          <button onClick={changeDescription}>{props.buttonText}</button>
        </div>
    )
}

export default Btc;

buttontext.css

@charset "utf-8";

.text{
    color: #ff0000;
}