[英]How do I take javascript identical functions and make then into a reusable function?
[英]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.