簡體   English   中英

如何導出函數並使它們在javascript / reactjs中可重用

[英]How to export functions and make them reusable in javascript / reactjs

我有一段代碼,幾乎可以在所有組件中使用它,並且工作得很好,但是我想使其可重用。

我試圖將其導出到另一個文件中,然后導入並在函數中傳遞參數,但是它不起作用。

searchTerm只是一個輸入,我將狀態設置為輸入的值。

const data = [
  {
    name: "User"
    email: "user@email.com"
    phone: 0000000
    gender: "male"
    notes: "some notes"
    birthday: "00/00/0000"
  }
]

我擁有並想要重用的內容:

let filteredData = []

if (clients.length > 0) {
  filteredData =
    data.filter(d=> Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
}

我試過的

export function tableFilter(data, searchTerm) {
  if (data.length > 0) {
    return data.filter(d => Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
  }
}

預期的結果是在所有組件中都使用該函數,而無需重寫它。 我現在得到的完全沒有數據。

解決方案非常簡單:

export function tableFilter(data, searchTerm) {
  let filteredData = []
  // the if check is not necessary 
  if (data.length > 0) {
    filteredData = data.filter(d => Object.values(d).join(' 
    ').toLowerCase().match(searchTerm.toLowerCase()))
  }
  return filteredData
}

為什么不在根組件中創建功能並將其傳遞給使用該功能的所有子組件。

class App extends React.Component {
  tableFilter(data, searchTerm) {
      if (data.length > 0) {
         return data.filter(d => Object.values(d).join('')
                                            .toLowerCase()
                                            .match(searchTerm.toLowerCase()))
       }
  }
  render() {
    return (<div>
             <Child1 myfilter={this.tableFilter} />
             <Child2 myfilter={this.tableFilter} />
             <Child3 myfilter={this.tableFilter} />
             <Child4 myfilter={this.tableFilter} />
             ...
           </div>);
  }
}

暫無
暫無

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

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