reactでstateの配列の分だけmapで回してcomponentにpropsで渡しています。
今回の例だと3こ配列の要素があるので3回失敗という文字が出てきます。
このやり方で特に問題はないのですが、
別の子のコンポーネントから親のstateを操作した場合、今回の子のコンポーネントまでpropsが
渡らないのでmapを外してrenderの中で
render() { return ( <Child data={{...this.state.arr}}/> ); }
とやればpropsが渡るみたいなので書き換えたいのですが
上記のスプレッド演算子を使うやり方だと配列の要素全てを返すためやりたいことができません。
配列の要素を一つずつ取得してpropsに渡したいのですがどうすればいいですか?
※コードは軽く省略させて頂いています
##コード
親コンポーネント
import Child from './Child'; class parent extends React.Component { constructor(props) { super(props); this.state = { arr: [ {test: '111', bool: false}, {test: '111', bool: false}, {test: '111', bool: false} ] } } aaa(obj) { return ( <Child data={obj} /> ); } render() { const component1 = this.state.arr.map((e) => { return ( this.aaa(e) ); }); return ( <div> {component1} </div> ); } } export default parent;
Child(子コンポーネント)
class Child extends React.Component { static propTypes = { data: PropTypes.object, }; constructor(props) { super(props); this.state = { index: this.props.data.bool } } render() { if (this.state.index) { return ( <div>成功</div> ); } return ( <div>失敗</div> ); } } export default Child;
「配列の要素を一つずつ取得してpropsに渡したい」の意図がよく分かりません。"data"という1つのプロパティには一つの値しか渡せません。
説明がおかしかったです。すみません。map以外の方法で配列の要素分componentを生成してpropsを渡したいってことです。今回で言うと1回目はthis.arr[0],2回目はthis.arr[1]と言う風な感じで渡したいと言うことです。
回答1件
あなたの回答
tips
プレビュー