React.jsでES6の文法を使って defaultProps などを設定する
環境
Tools | Version |
---|---|
react-tools | 0.13.1 |
jsx | 0.12.2 |
react.js | 0.13.1 |
JSXTransformer.js | 0.13.1 |
react-tools
をnpm
でインストールし、jsx
に--harmony
オプションを付けてコンパイルした。
npm install -g react-tools
jsx --harmony -w src build
方法
var Hello = React.createClass({
getDefaultProps: function() {
return {name: "Default Props"};
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
を
class Hello extends React.Component {
constructor(props) {
super(props);
console.log(props);
console.log(this.props);
this.state = {name: this.props.initialName};
}
render() {
return <div>Hello {this.state.name}</div>;
}
}
Hello.defaultProps = {initialName: "Default Props"};
にする。
詳細
普通にdefaultPropsを記述すると、
var Hello = React.createClass({
getDefaultProps: function() {
return {name: "Default Props"};
},
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
となる。
これを、ES6で記述すると、
class Hello extends React.Component {
getDefaultProps() {
return {name: "Default Props"};
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
となるとおもいきや、defaultProps
が全然効かない。
Reusable Componentsのドキュメントを読むと、propTypes
とdefaultProps
やpropTypes
はどうやら書き方がちょっと違うらしい。
The API is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.
Another difference is that propTypes and defaultProps are defined as properties on the constructor instead of in the class body.
サンプルを見ながら書き換える。
export class Hello extends React.Component {
constructor(props) {
super(props);
console.log(props);
console.log(this.props);
this.state = {name: this.props.initialName};
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
Hello.defaultProps = {initialName: "Default Props"};
コンパイルは通るが、ブラウザで表示すると以下の様なエラーが出る。
Uncaught Error: Parse Error: Line 3: Illegal export declaration
at file:///Users/yoshiki_aoki/work/react-tutorial/build/alone.js:3:undefined
export var ____Classm=React.Com ...
^
ちなみに、React.jsのページにあるJSX Compilerで、ドキュメントに載っているコードをコンパイルすると同じエラーが出る。
試しにexport
をはずすと、エラーは発生しないがデフォルト値がセットされていない。
これは、別の箇所が原因でrender
のprops
をstate
に変更するのを忘れていた事が原因だった。
class Hello extends React.Component {
constructor(props) {
super(props);
console.log(props);
console.log(this.props);
this.state = {name: this.props.initialName};
}
render() {
return <div>Hello {this.state.name}</div>;
}
}
Hello.defaultProps = {initialName: "Default Props"};
これで無事表示された。
References
Author And Source
この問題について(React.jsでES6の文法を使って defaultProps などを設定する), 我々は、より多くの情報をここで見つけました https://qiita.com/ringo/items/3d8b693fec7395b913ef著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .