私はカスタムテキストページングコンポーネントを作成しました(現在のページネーション情報を表示しています、例えば1-Nの合計)、繰り返しコンポーネントをComponentAとComponentBに追加しました。 TextPaginationコンポーネントを親コンポーネントに追加する必要があるたびに、同じ状態とコールバックメソッドを追加する必要があります。 ComponentAとComponentBを見ると、どちらもthis.state = {itemCount:0}とonDisplayLessDataとonDisplayMoreDataコールバックメソッドを持っています。これは私が避けたいものです。特に、他の開発者がTextPaginationコンポーネントを使用する必要がある場合は、これらをすべて追加することを忘れないでください。Reactでサブクラス化
成分A
class ComponentA extends React.Component {
constuctor() {
super();
this.state = { itemCount: 0 }
}
render(){
// re-render data
<TextPagination .../>
}
onDisplayMoreData(){}
onDisplayLessData(){}
}
成分B
class ComponentB extends React.Component {
constuctor() {
super();
this.state = { itemCount: 0 }
}
render(){
// re-render data
<TextPagination .../>
}
onDisplayMoreData(){ //when child updates, this gets called }
onDisplayLessData(){ //when child updates, this gets called }
}
class TextPagination extends React.Component {
constructor() {
super();
this.state = { itemCount: 0, showLess: false };
this.displayMoreData = this.displayMoreData.bind(this);
this.displayLessData = this.displayLessData.bind(this);
}
render() {}
displayMoreData(value) {
// more code
// callback to notify the parent component
this.props.onDisplayMoreData(value);
}
displayLessData(value) {
// more code
// callback to notify the parent component
this.props.onDisplayLessData(value);
}
}
だから、私はthis.state =とページ区切りと呼ばれる別のクラスを作成するために、図TextComponentに{ITEMCOUNT個:0}コールバックメソッドを呼び出し、それをReact.Componentまで拡張します。次に、ComponentAとComponentBはPaginationクラスから拡張できます。
例:
class Pagination extends React.Component {
constructor() {
super();
this.state = {
itemCount: 0
};
this.onDisplayMoreData = this.onDisplayMoreData.bind(this);
this.onDisplayLessData = this.onDisplayLessData.bind(this);
}
onDisplayMoreData(itemCount) {
this.setState({
itemCount: itemCount
});
}
onDisplayLessData(itemCount) {
this.setState({
itemCount: itemCount
});
}
}
ComponentA extends Pagination {
constructor() { super(); }
render() {
// re-render data
<TextPagination .../>
}
}
ComponentB extends Pagination {
constructor() { super(); }
render() {
// re-render data
<TextPagination .../>
}
}
このアプローチには何の問題もなく動作しているようです。 ComponentAとComponentBは、もはや状態とコールバックメソッドを持つ必要はありません。他の開発者は、TextPaginationを使用するときに状態とコールバックメソッドを追加する必要はありません。
これは適切な解決策ですか?そうでない場合は、助けてください。
私は、ComponentAまたはComponentBが追加の状態を追加する必要がある場合は、元の親の状態を上書きします...正しいのですか?
ありがとうございました!
2つの選択肢について考えてみましょう:1)純粋に保ち、小道具が渡され(状態なし)、あなたがコールバックを起動して、実装者に状態を変更させるように変更する小道具が必要な場合。 2)状態を使用しますが、あなたのトップレベルに保ち、小道具として渡します。ページインデックスをインクリメントすると、親にコールバックする必要があります –
ありがとう、これは私が親と子の両方のコンポーネントに状態を持っていることに気付くかもしれません。私はリファクタリングの少しをする必要があります。 – FNMT8L9IN82