我的组件(嵌套)结构看起来像这样:
- 容器
- 组件A
- 组件B
- ComponentC(想要在这里处理事件,状态存在于容器上)
- 组件B
- 组件A
我是否需要从 Container、ComponentA、ComponentB 和最后的 ComponentC 一直作为 props 传递才能拥有这个处理程序?还是有另一种方法,例如使用 Context API?
因此,我发现使用 react.js 和 vue.js/angular.js 处理事件有点困难。
我的组件(嵌套)结构看起来像这样:
我是否需要从 Container、ComponentA、ComponentB 和最后的 ComponentC 一直作为 props 传递才能拥有这个处理程序?还是有另一种方法,例如使用 Context API?
因此,我发现使用 react.js 和 vue.js/angular.js 处理事件有点困难。
我建议使用Context API(如您所提到的)或高阶组件(HoC)
Context Api 是您的数据中心。您将应用程序需要的所有数据和点击事件放在这里,然后使用“Consumer”方法在任何组件中获取它们,而不管它是如何嵌套的。这是一个基本示例:
context.js //in your src folder.
import React, { Component, createContext } from "react";
import { storeProducts } from "./data"; //imported the data from data.js
const ProductContext = createContext(); //created context object
class ProductProvider extends Component {
state = {
products: storeProducts,
};
render() {
return (
<ProductContext.Provider
//we pass the data via value prop. anything here is accessible
value={{
...this.state,
addToCart: this.addToCart //I wont use this in the example because it would
be very long code, I wanna show you that, we pass data and event handlers here!
}}
>
// allows all the components access the data provided here
{this.props.children},
</ProductContext.Provider>
);
}
}
const ProductConsumer = ProductContext.Consumer;
export { ProductProvider, ProductConsumer };
现在我们使用 .Consumer 和 .Provider 方法设置我们的数据中心,以便我们可以通过组件中的“ProductConsumer”访问这里。假设您想在主页中显示所有产品。产品列表.js
import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../context";
class ProductList extends Component {
render() {
return (
<React.Fragment>
<div className="container">
<div className="row">
<ProductConsumer>
//we fetch data here, pass the value as an argument of the function
{value => {
return value.products.map(product => {
return <Product key={product.id} />;
});
}}
</ProductConsumer>
</div>
</div>
</React.Fragment>
);
}
}
export default ProductList;
这是 Context Api 背后的逻辑。这听起来很可怕,但如果你知道其中的逻辑,那就很简单了。与其在每个组件内部创建数据和事件处理程序,还不如在props钻取中创建一个令人头疼的问题,只需将数据和事件处理程序放在这里并进行编排即可。
我希望它有帮助。