当函数是字符串时如何呈现 [英] How to render when the function is a character string

查看:67
本文介绍了当函数是字符串时如何呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用React的渲染处理时遇到问题。
有一个名为func1和func2的函数,在渲染时调用(例如: return(< func1 />))。

I'm having trouble with React's Render processing. There is a function called func1 and func2, which is called when rendering (eg: return (<func1 />)).

例如,我想从JSON值中funcName的字符串渲染为实际的函数名,如下所示,我该怎么做?

For example, I want to render as the actual function name from the character string at funcName in the JSON value like the following, how can I do it?

{funcName: "func1"}

如果是上述值,

我想呈现为 return(< func1 />)

虽然我试图解决这个问题,但即使它被eval使用或在变量中渲染它也会导致错误。

Although I tried to solve this problem, even if it is used by eval or rendering it in a variable it will result in an error.

为什么现在要进行此处理是通过以下处理进行渲染,因为它很麻烦,因为每次添加新函数时都需要添加if语句。

Why do you want to do this processing now is rendering with the following processing, because it is troublesome because you need to add an if statement every time you add a new function.

if (funcName.func1! = null) {
  return `<func1 />`
} else if (funcName.func2! = null) {
  return `<func2 />`
} 

每次添加函数时都会添加if语句
即可。

An if statement is also added each time a function is added that's all.

如果你知道,请回答。

推荐答案

首先,React组件名称必须以大写字符开头,请查看此问题以获取更多详细信息

Firstly, React components name must begin with uppercase character, check this question for more details

React - 用户定义的JSX组件无法呈现

其次而不是存储

{funcName: "Func1"}

你要存储

{funcName: Func1}

然后呈现像

render() {
    const Func1  = obj.funcName;
    return <Func1/>
}

或者如果你不能用数据中的组件替换字符串,你会做什么

or if you can't replace the string with component in your data, you would do

render() {
    const Func1  = eval(obj.funcName);
    return <Func1/>
}

这篇关于当函数是字符串时如何呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆