React 関数を子コンポーネントに渡す
地味にここつまりました
この入力フィールドに入れた値を更新している
import React from 'react'; import logo from './logo.svg'; import './App.css'; class App extends React.Component { constructor(props) { super(props) this.state = { value: '' } } handleValue(e) { this.setState({value: e.target.value}) } render () { return ( <div className="App"> <input type="text" onChange={(e) => this.handleValue(e)}/> </div> ); } } export default App;
これに子コンポーネントに関数を渡して更新する
下記みたいに、メソッドを渡すと、TypeError: Cannot read property 'setState' of undefinedとエラーがでる。 理由は、thisがAppを識別できていない
const Form = (props) => ( <input type="text" onChange={props.handleValue}/> ) class App extends React.Component { constructor(props) { super(props) this.state = { value: '' } } handleValue(e) { this.setState({value:e.target.value}) } render () { return ( <div className="App"> <Form handleValue={this.handleValue}/> </div> ); } } export default App;
修正方法
関数をbind thisすると解消される
const Form = (props) => ( <input type="text" onChange={props.handleValue}/> ) class App extends React.Component { constructor(props) { super(props) this.state = { value: '' } this.handleValue = this.handleValue.bind(this) } handleValue(e) { this.setState({value:e.target.value}) } render () { return ( <div className="App"> <Form handleValue={this.handleValue}/> </div> ); } } export default App;
あるいはこれでもいけるみたい。こっちの方が良いですね
<Form handleValue={this.handleValue.bind(this)}/>