1
1

More than 3 years have passed since last update.

Reactのrender()内で、コンポーネントの引数に数値を渡す方法

Posted at

盲点でした。

react-railsの環境では、以下のようなコマンドで簡単にコンポーネントの雛形が作れます。
bundle exec rails g react:component sampleComponent id:number name:string

こうして作られたファイルの中身は以下のようになります。

SampleComponent.js

import React from "react"
import PropTypes from "prop-types"
class SampleComponent extends React.Component {
  render () {
    return (
      <React.Fragment>
        Id: {this.props.id}
        Name: {this.props.name}
      </React.Fragment>
    );
  }
}

SampleComponent.propTypes = {
  id: PropTypes.number,
  name: PropTypes.string
};
export default SampleComponent

ここで、idの型をnumberとしてみたはいいものの、render()内で実際にSampleComponentを使う際はどうやって値を渡すのでしょう?

ダメな方法

stringさんは、以下の方法で渡せます。
<SampleComponent name="hoge" />

が、numberさんを以下のように書いてしまうと、エラーになります。
<SampleComponent id="10" />

解決方法

中かっこ("{}")で囲みます。
そうか、数値リテラルを渡すのだから、こうなるんですね。
思いつかなかった。。
<SampleComponent id={10} />

1
1
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
1