是否可以使用特定类型定义功能组件?
我有一个功能组件,可以与不同种类的模型结构一起使用。
假设该模型可以是tmodel
。
请参阅下面的一些代码来解释情况:
interface MyCompProps {
model: TMODEL,
records?: TMODEL[],
// other stuff...
}
const MyComp = (props: MyCompProps) => {
// component code comes here...
// this component code needs TMODEL to be used in various ways
// like for e.g. see below
const [record, setRecord] = useState<TMODEL>(props.model);
const load() {
// load data from ajax
const data = loadAjax('model-specific-endpoint...');
// build record from model and set state
setRecord(new TMODEL(data));
}
// in the render, it may also be useable...
return (
<React.Fragment>
...
Record ID: {record.id}
...
</React.Fragment>
);
};
另外,如果我能够在上述代码中定义tmodel
,我想这就是我如何能够使用它的方式:
// some component code...
const cat = new CatModel(...);
// some component code...
return (
...
<MyComp model={cat} />
...
);
// some component code...
是否有这样的方法可以实现那?还是有更好的方法使组件特定于类型?
I have a functional component that can work with different kinds of model structures.
Lets assume that the model can be TMODEL
.
See below some code to explain the situation:
interface MyCompProps {
model: TMODEL,
records?: TMODEL[],
// other stuff...
}
const MyComp = (props: MyCompProps) => {
// component code comes here...
// this component code needs TMODEL to be used in various ways
// like for e.g. see below
const [record, setRecord] = useState<TMODEL>(props.model);
const load() {
// load data from ajax
const data = loadAjax('model-specific-endpoint...');
// build record from model and set state
setRecord(new TMODEL(data));
}
// in the render, it may also be useable...
return (
<React.Fragment>
...
Record ID: {record.id}
...
</React.Fragment>
);
};
Also if I am able to define the TMODEL
in above code, I guess this is how how I could be able to use it:
// some component code...
const cat = new CatModel(...);
// some component code...
return (
...
<MyComp model={cat} />
...
);
// some component code...
Is there such a way to achieve that? Or is there a better approach to make a component a type specific?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用类实现来迫使您的组件的消费者按某些道具的类型规则遵守。
例如,您可以拥有类似的东西:
然后,在要使用此通用组件时,在外部组件中,您可以定义任何自定义类,但需要实现抽象类。例如:
You can use class implementations in order to force consumer of your component to abide by type rules for certain props.
For example, you can have something like this:
Then, in your outer component when you want to consume this generic component, you can define any custom class but it is required to implement abstract class. For example: