How to render when the function is a character string

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 />)).

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"}

If it is the above value,

I want to render as "return (<func1 />)"

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.

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 />`

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

Please answer if you know.



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

React - User-Defined JSX Components Not rendering

Secondly instead of storing

{funcName: "Func1"}

you would store

{funcName: Func1}

and then render like

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/>

Instead of putting it as element <func2 /> call the function func2()
But you func2 must return a valid react element.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.