障害
React の Class を呼ぼうとすると、ブラウザ環境でエラーが発生し、呼出に失敗します。
環境
firefox 56 & chrome 62
babel-core 5.8.38
react 15.6.2
react-dom 15.6.2
症状
React の React.Component 拡張 Class の 呼出に失敗します。
エラーが発生する要因がどうにも解りません。
- (ファイル) render.jsx:
class CompClock extends React.Component {
.....
}
a) document.Hello = CompClock; // -> 意図した動作をする
b) document.Hello = <CompClock/>; // -> ブラウザで下記のエラーが出る
- firefox console からのキャプチャ
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (react-dom.js:17859)
at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (react-dom.js:15950)
at ReactCompositeComponentWrapper.performInitialMount (react-dom.js:4770)
at ReactCompositeComponentWrapper.mountComponent (react-dom.js:4661)
at Object.mountComponent (react-dom.js:11409)
at mountComponentIntoNode (react-dom.js:9646)
at ReactReconcileTransaction.perform (react-dom.js:14573)
at batchedMountComponentIntoNode (react-dom.js:9668)
at ReactDefaultBatchingStrategyTransaction.perform (react-dom.js:14573)
at Object.batchedUpdates (react-dom.js:8729)
詳細
React の学習を兼ねたコードを作成して挙動の調査を進めています。
今後を踏まえ、React.Component の拡張 Class を作成 (render.jsx) し、現在時刻をリアルタイム(秒単位)にブラウザへ表示するコードを作成しました。
document.Hello = "React Class" としてインスタンスを投入し、index.xhtml から、document.Hello を呼び出してレンダリングさせています。
render.jsx "a)" の記載方法の場合は問題無く秒単位で表示が変わるのですが、同 "b)"の場合 "症状"に記載のエラーが表示されて表示がされません。
何となく "new CompClock" のようなケースの時に NG のように思えますが、確証はありません。
尚、フェーズとしては各種技術の実験段階ですので、代替え案云々と言う事は考えていません。
ソースコード
- (ファイル) index.xhtml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>05</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <script src="https://unpkg.com/react@15/dist/react.js"></script> <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.38/browser.js"></script> <script src="render.jsx" type="text/babel"></script> </head> <body> <div id="root"></div> <script type="text/babel"> ReactDOM.render( React.createElement(document.Hello), document.getElementById('root') ); </script> </body> </html>
- (ファイル) render.jsx:
class CompClock extends React.Component { constructor(props) { super(props); this.state = { now: (new Date()) }; setInterval(e => { this.setState({now: (new Date())}); }, 1000); } fmt(v) { const s = "00" + v; return(s.substr(s.length - 2, 2)); } render() { // const now = this.state.now; const now = new Date(); const hh = this.fmt(now.getHours()); const mm = this.fmt(now.getMinutes()); const ss = this.fmt(now.getSeconds()); return( <div>{hh}:{mm}:{ss}</div> ); } }; console.log("start.."); // document.Hello = CompClock; document.Hello = <CompClock/>;
回答2件
あなたの回答
tips
プレビュー