LoginSignup
1
0

More than 3 years have passed since last update.

【TypeScript】Reactでちゃんと型を指定したい

Posted at

コールバックなどの型をanyにしないために。

Reactの範囲だけでなく一般のtsの記述もあります。

Reactは名前Reactでimportしていることとします。

props, state

コンポーネント作成時にpropsで受け取る型とstateの型を指定する。

// ジェネリクスで<propsの型, stateの型>を指定する
class Hello extends React.Component<{user: string}, {greeting: string}> {
  constructor(props: {user: string}) {
    super(props);
    this.state = {greeting: 'Good morning'};
  }

  render() {
    return (<p>{this.state.greeting} {this.props.user}!</p>)
  }
}

// 使う側
class TestComponent extends React.Component {
  render() {
    const elem: React.ReactNode = <p>Hello React</p>
    return (
      <Hello user="kide"/>
    )
  }
}

事前にtypeを宣言しておくこともできる。

type userInputPropsType = {
  name: string,
  onNameChanged: (arg0: React.ChangeEvent<HTMLInputElement>)=>void
}
class UserInput extends React.Component<userInputPropsType, {}> {
  render() {
    return (
      <input value={this.props.name} onChange={this.props.onNameChanged} />
    )
  }
}

コールバック

イベントはReact.ChangeEvent, React.MouseEventなどで引数を受け取る。
ジェネリクスで要素を指定するが、ちゃんと指定しないとtarget.valueなどを参照できなくなる。

受け取れるイベントの確認は公式ドキュメントで。

class UserButton extends React.Component<{}, {userName: string}> {
  nameChanged = (event: React.ChangeEvent<HTMLInputElement>)=>{
    this.setState({userName: event.target.value});
  }

  buttonPressed = (event: React.MouseEvent<HTMLButtonElement>)=>{
    alert(this.state.userName);
  }

  render() {
    return (
      <div>
        <input onChange={this.nameChanged} />
        <button onClick={this.buttonPressed}>Click!</button>
      </div>
    )
  }
}

要素の受け取り

childrenで描画する時はReact.ReactNode型で受け取る。

// propsでchildrenを受け取るようにする。
// 他のプロパティも受け取れる(color)
class ColorPane extends React.Component<{children: React.ReactNode, color: string}, {}> {
  render() {
    return (
      <div style={{background: this.props.color}}>
        {this.props.children}
      </div>
    )
  }
}

// 使う側
class TestComponent extends React.Component {
  render() {
    const elem: React.ReactNode = <p>Hello React</p>
    return (
      <div>
        <ColorPane color="blue">
          <h1>Blue Pane</h1>
          <p>This is blue pane text</p>
        </ColorPane>

        <ColorPane color="red">
          <h1>Red Pane</h1>
          <p>This is red pane text</p>
        </ColorPane>
      </div>
    )
  }
}
1
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
1
0