我已经创建了一个子组件和一个父组件,子组件从循环中被调用,事件处理程序也从prop中被调用,但是当我从子组件中单击navlink时,每个点击事件都会被调用
如果调用了第一个navlink,则仅应调用第一个navlink的处理程序。
import { NavLink } from "react-router-dom";
import React, { Component } from "react";
import axios from "axios";
// import SearchComponent from "../Common/SearchComponent";
// import Navbar from "../Common/Navbar";
import { CompanyId } from "../../locales/global.json";
import CategoryComponent from "./CategoryComponent";
class CategoryPageComponent extends Component {
state = {
Categories: []
};
componentDidMount() {
if (this.state.Categories.length === 0) this.bindCategoryData();
}
onCategorySearch = e => {
if (this.state.Categories.length === 0 && e === "")
this.bindCategoryData(0);
};
bindCategoryData = () => {
var $this = this;
axios
.post(
"http://fstrumplifyml.azurewebsites.net/api/ApiCategory/GetCategories",
{
companyid: CompanyId,
languageid: 1
}
)
.then(function(response) {
$this.setState({
Categories: response.data.Data
});
});
};
UpdateSubCategories = (categories, categoryId) => {
console.log(categories);
};
renderCategoryComponent = category => {
return (
<CategoryComponent
Category={category}
OnUpdateSubCategories={this.UpdateSubCategories.bind(this)}
/>
);
};
render() {
return (
<React.Fragment>
{/* <Navbar /> */}
<section className="space--sm">
<div className="container">
{/* <SearchComponent onSearch={this.onCategorySearch} /> */}
<div className="row">
{this.state.Categories.map(this.renderCategoryComponent)}
</div>
</div>
</section>
</React.Fragment>
);
}
}
export default CategoryPageComponent;
import React, { Component } from "react";
import { NavLink } from "react-router-dom";
class CategoryComponent extends Component {
render() {
return (
<div className="masonry__item col-md-4 filter-computing">
<div className="product">
<NavLink
to={this.props.OnUpdateSubCategories(
this.props.Category.SubCategories,
this.props.Category.CategoryId
)}
>
<img
alt={this.props.Category.CategoryName}
className="ProductImage"
src={this.props.Category.ImageUrl}
/>
</NavLink>
<NavLink
className="block"
to={this.props.OnUpdateSubCategories(
this.props.Category.SubCategories,
this.props.Category.CategoryId
)}
>
<div>
<h5>{this.props.Category.CategoryName}</h5>
</div>
</NavLink>
</div>
</div>
);
}
}
export default CategoryComponent;
答案 0 :(得分:0)
<NavLink
className="block"
to={this.props.OnUpdateSubCategories(
this.props.Category.SubCategories,
this.props.Category.CategoryId
)}
>
将函数调用放在props中时,每次render()
运行时都会调用它
您可以在道具中使用箭头功能
to={
()=>{this.props.OnUpdateSubCategories(
this.props.Category.SubCategories,
this.props.Category.CategoryId
)}
}
但是将在每个渲染器中创建一个函数实例
因此最好在CategoryComponent
内创建一个函数