閲覧いただき、ありがとうございます。
子コンポーネントで setState()
して、親コンポーネントのstateを変更したいのですが、できるものとできないものがあり、困っています。
具体的には、下記ソースコードの items
は変更できているのですが、 mainIndex
は変更できていません。
JavaScript
1// App.js 2 3import PrimaryItem from "./components/PrimaryItem"; 4 5class App extends Component { 6 constructor(props) { 7 super(props); 8 this.state = { 9 items: { 10 0: { 11 id: 1, 12 color: "red" 13 }, 14 1: { 15 id: 2, 16 color: "blue" 17 } 18 }, 19 // mainIndexを変更したい 20 mainIndex: 0 21 } 22 } 23 24 render() { 25 return( 26 <PrimaryItem items={this.state.items} mainIndex={this.state.mainIndex} 27 ); 28 } 29}
JavaScript
1// PrimaryItem.js 2 3class PrimaryItem extends Component { 4 5 _clickColor = id => () => { 6 const items = [...this.props.items]; 7 const item = items.find(item => item.id === id); 8 item.color = "black" 9 this.setState({ 10 item 11 mainItemIndex: item.number 12 }); 13 }; 14・・・ 15}
mainIndexをsetStateする前に変更しようと思い、下記のようにやってみたのですが
JavaScript
1 _clickColor = id => () => { 2 const items = [...this.props.items]; 3 const item = items.find(item => item.id === id); 4 const mainIndex = this.props.mainIndex 5 item.color = "black" 6 mainIndex = item.number 7 this.setState({ 8 item 9 mainItemIndex 10 }); 11 };
エラーが出てしまいました。
Syntax error: "mainIndex" is read-only
すみませんが、どなたかお知恵を拝借させていただければと思います。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/21 11:11