簡體   English   中英

從類轉換為具有組合父子的功能組件

[英]converting from classes to Functional component with composition parent-child

我正在嘗試將帶有 inheritance 的 React 類轉換為功能組件,並且不會錯過任何功能。 到目前為止,我閱讀了大量文章,但無法弄清楚如何做到這一點。 主要問題是我的父組件修改了子組件的 state。

# Base class
class BaseTable extends React.Component {

  // function to filter table when search text is changed
  _onChangeText = (ev, text) => {
    // storing filterText as a state, so onDropdownChange() can refresh filter
    this.setState({ filterText: text });

    if (this.state.items[0] && this.state.items[0].hasOwnProperty(this.state.filterBy)) {
      // refreshing the filteredItems array with new query
      this.setState({
        filteredItems: text ? this.state.items.filter(item => item[this.state.filterBy].toLowerCase().indexOf(text.toLowerCase()) > -1) : this.state.items,
        selectedPageIndex: 0

      });
    }
  };
}

export default BaseTable;

子 class 擴展它並通過使用this引用使用父 class 的方法:

class SpecificTable extends BaseTable {
  constructor(props) {
    super(props);
  }

this.state = {
      items: [],
      filteredItems: [],
      filterText: "",
      selectedPageIndex: 0,
      isError: false,
      errMsg: ''
    };

return (
<TextField
 label="Search Query:"
 onChange={this._onChangeText}
 styles={controlStyles}
 value={this.state.filterText}
 />
);
}

export default SpecificTable;

目標是將其轉換為沒有類的功能組件並重用 BaseTable 中的這些函數,因為我有一些“特定表”。 我正在考慮創建 ReactContext 但仍然遇到問題。

編輯:添加鏈接到我關於inheritance 組成的評論

在功能組件中,您可以通過創建一個可重用的鈎子來實現,該鈎子可由以前擴展 BaseTable 的各種表組件使用


const useBaseTable = () => {

   const [state,setState] = useState(your_base_state);

   const onChangeText = useCallback((arg) => {
      ... your onChangeText
   },[...relevant dependencies]);

   // return your state, setState (if necessary), and your callback 
   // in reality, you can return whatever you want from this hook
   return [state, setState, onChangeText];
}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM