我的目标是如果我传递这样的道具:modalService.getContent('my_element1', {someProp: 'someProp'})
然后我的内容应该返回***COMPONENT 1***
我在React文档中查看了渲染道具,但没有找到我要找的答案,有人知道如何找到解决这个问题的方法吗?
const TesterElement1 = () => {
return <div>***COMPONENT 1***</div>;
};
const TesterElement2 = () => {
return <div>***COMPONENT 2***</div>;
};
const TesterElement3 = () => {
return <div>***COMPONENT 3***</div>;
};
export class ModalService {
getContent(contentType, prop) {
const content = {
my_element1: (props) => <TesterElement1 info={props} />,
my_element2: (props) => <TesterElement2 info={props} />,
my_element3: (props) => <TesterElement3 info={props} />,
};
return content[contentType](prop);
}
}
我试图渲染一个特定的元素在一个不同的组件基于属性给予ModalService,像这样:
const myNewElement = ({ type, prop }) => {
const modalService = new ModalService();
const content = modalService.getContent(type, prop);
return (
{content}
)
}
如果我运行代码片段,我得到这个错误:"Uncaught SyntaxError: Unexpected token '<'"
如果我看一下控制台,我得到这个错误:"Uncaught TypeError: content[contentType] is not a function"
当我检查我的沙箱时,它会按预期工作。
我正在重用使用webpack构建的旧代码,并试图用Vite 4从头开始重建它。我想知道这是不是它不像预期的那样工作的原因。
设法消除错误并找到临时解决方案。在此声明中,我将const content = modalService.getContent(type, prop);
更改为const content = modalService.getContent('my_element1', prop);
。