##Reactのstateに関数を保持しても良いか
stateに時クラスの関数を設定しているのですが、stateは変更されてしまう可能性があるので、
関数のような変更されることを前提にしない値はstateで保持するのはよくない記述でしょうか。
##なぜそのような書き方をしているか
画面に複数個のボタンを表示させるが、ボタン用の共通ファイルを使用して、そのファイルにpropsで各ファンクションを渡して、ボタンの機能を変えております。
####ソース
親クラス
class App extends Component { constructor(props) { super(props); this.state = { //ファンクションリスト function: { getAllItems: this.getAllItems, itemDelete: this.itemDelete, itemUpdate: this.itemUpdate }, this.getAllItems = this.getAllItems.bind(this); this.itemsSearch = this.itemsSearch.bind(this); this.itemDelete = this.itemDelete.bind(this); }; //全件取得ファンクション getAllItems = () => { ~省略~ } itemDelete = () => { ~省略~ } itemUpdate = () => { ~省略~ } render() { return ( <div className="App"> <Child function={this.state.function} /> </div> ); } }
子クラス
const child = (props) => ( <div> <Button function={props.function.getAllItems} /> <Button function={props.function.itemsSearch} /> <Button function={props.function.itemDelete} /> </div> }
ボタンクラス
import React from 'react'; function Button(props) { return ( <div> <button onClick={()=>{props.function()}}> ボタン </button> </div> ); } export default Button;
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/02 05:28