前提・実現したいこと
構成
親コンポーネント(タブバー描画)
|-- HomePage タプ
`-- SettingsPage タブ
HomePageコンポーネントでのイベント発火で親コンポーネントの state を更新し、それをもう一つの SettingsPageコンポーネントへ props として渡したいのですが渡せません。
発生している問題・エラーメッセージ
該当のソースコード
JavaScript
1// App.js 2 3import React, {Component} from 'react'; 4import PropTypes from 'prop-types'; 5import {Page, Tab, Tabbar, Button} from 'react-onsenui'; 6 7import 'onsenui/css/onsenui.css'; 8import 'onsenui/css/onsen-css-components.css'; 9import './App.css'; 10 11// HomePage タブ 12const HomePage = (props) => ( 13 <Page> 14 <Button onClick={props.omikuji}>Click !</Button> 15 </Page> 16); 17HomePage.propTypes = { 18 omikuji: PropTypes.func, 19}; 20 21// SettingsPage タブ 22const SettingsPage = (props) => ( 23 <Page> 24 {props.scores.map((score) => ( 25 <div key={score.created_at}>{score.fortune}</div> 26 ))} 27 </Page> 28); 29SettingsPage.propTypes = { 30 scores: PropTypes.arrayOf( 31 PropTypes.shape({ 32 created_at: PropTypes.instanceOf(Date), 33 fortune: PropTypes.string, 34 }) 35 ), 36}; 37 38// 親コンポーネント 39class App extends Component { 40 state = {scores: []}; 41 scoreItems = []; 42 43 // タブの描画 44 renderTabs = () => { 45 return [ 46 { 47 content: <HomePage key="Home" omikuji={this.handleOnClick} />, 48 tab: <Tab key="Home" label="Home" icon="md-home" />, 49 }, 50 { 51 content: <SettingsPage key="settings" scores={this.state.scores} />, 52 tab: <Tab key="settings" label="Settings" icon="md-settings" />, 53 }, 54 ]; 55 }; 56 57 // HomePage タブのボタンクリックでイベント発火 58 handleOnClick = () => { 59 const fortunes = ['大吉', '吉', '中吉', '小吉', '末吉', '凶', '大凶']; 60 let num = Math.floor(Math.random() * fortunes.length); 61 this.scoreItems.unshift({ 62 fortune: fortunes[num], 63 created_at: new Date(), 64 }); 65 this.setState({scores: this.scoreItems.slice()}); 66 }; 67 68 render() { 69 return <Tabbar renderTabs={this.renderTabs} />; 70 } 71} 72 73export default App; 74
試したこと
・コンストラクタ内の scoreItems 変数を props にすると SettingsPage には渡ります
・しかしそれでも SettingsPage 内の <Page /> では "children: Array[0]" となってしまいます
補足情報(FW/ツールのバージョンなど)
$ node -v
v10.14.2
$ npm -v
6.5.0
create-react-app@2.1.2
react(-dom)@16.7.0
onsenui@2.10.6
react-onsenui@1.11.2
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/30 20:29
2018/12/30 21:08