[英]Strategy pattern with React component
I'm trying to use the strategy pattern inside a react component to render different functions instead of using a switch case just for learning purposes but i'm not sure where to start.我正在尝试使用 react 组件中的策略模式来呈现不同的功能,而不是仅出于学习目的使用 switch case,但我不确定从哪里开始。
Would it be a good way to do it?这会是一个很好的方法吗?
const renderField = () => {
switch (field) {
case 1:
return first();
case 2:
return second();
default:
return third();
}
};
return <div>{renderField()}</div>;
you would just use React children
.你只会使用 React children
。 Strategy Pattern is a way to not need to change the base component but change some behaviour dynamically from the ouside.策略模式是一种不需要更改基本组件但从外部动态更改某些行为的方法。
const MyComponent = ({children}) => <div>{children}<div>
<MyComponent><FirstComponent></FirstComponent></MyComponent>
However if you want to pass in a children based on some other values eg 1, 2, 3
.但是,如果您想根据其他一些值(例如1, 2, 3
传入孩子。
you could create a Object that holds their Relations to the components:您可以创建一个对象来保存它们与组件的关系:
const componentMap = {1: <FirstComponent/>, 2: <SecondComponent/>}
and then use it like this:然后像这样使用它:
<MyComponent>{componentMap[index]}</MyComponent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.