MENU

React Typescript 最低限で戦う為の基本

クラスコンポーネント関数コンポーネント

// props とstateの型を宣言する

type Todo ={
  id:number
  body: string
}

type TodosState = {} // ここは特になければオブジェクトを受け取る

type TodosProps = {
  todos: Todo[]
}

class Todos extends React.Component<TodoProps, TodoStete>{

}
type TodoItemProps = {
  id: number
  body: string
}

type Todo = {
  id: number
  body: string
}
const TodoItem: React.FC<TodoItemProps> = (props) => {
  return(<div key={props.id}>{props.body}</div>)
}

React での基本的型つけ

イベントの型とか最初はどうするのかと思った

type AppState = {
  value: string
}

class App extends React.Component<{}, AppState> {
  constructor(props: any){
    super(props)
    this.state ={
       value: ''
    }
  }

  handleValue(e: React.FormEvent<HTMLFormElement>): void{
    this.setState({value: e.target.value})
  }
  
  handleSubmit(e: React.ChangeEvent<HTMLInputElement>): void {
    e.preventDefault()
    alert(this.state.value)
  }

  render(){
   return (
    <div>
      <form onSubmit={this.handleSubmit.bind(this)}>
         <input type="text" onChange={this.handleValue.bind(this)}/>
         <input type="submit" value ="送信"/>   
      </form>
    </div>
   )
  }
}

type handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>  void
type handleSubmit = (event: React.FormEvent<HTMLFormElement>) =>  void

type FormProps = {
  handleTodoValue: handleChange
  handleSubmit: handleSubmit
}

const Form: FC<FormProps> = (props) => {
  return(
    <div>
      <form onSubmit={props.handleSubmit}>
        <input type="input" onChange={props.handleTodoValue}/>
        <input type="submit" value="追加"/>
      </form>
    </div>
  )
}

export default Form

参考

qiita.com