简体   繁体   English

使用 .map (React) 将 JSX 字符串转换为 JSX 表达式

[英]Convert JSX string to JSX expression with .map (React)

I need to change this data that is passed into a component我需要更改传递到组件中的数据

columns={[{
    name: "Fund Name",
        width: "40%"
    }, {
        name: "Review Date",
        width: "20%"
    }, {
        name: "Company Debt",
        width: "20%"
    }, {
        name: "Alerts",
        width: "10%"
    }, {
        name: "Actions",
        width: "10%",
        options: 'customBodyRender: (value, tableMeta, updateValue) => { return (<Options />);'
    }]
}

to this inside the component...到这个组件内部...

const columns = [{
            name: "Fund Name",
        }, {
            name: "Review Date"
        }, {
            name: "Company Debt"
        }, {
            name: "Alerts",
        }, {
            name: "Actions",
            options: {
                customBodyRender: (value, tableMeta, updateValue) => {
                    return ( <Options /> );
                }
            }
        }
    }];

Basically I've got this far....基本上我已经到了这一步......

let columns = this.props.columns.map((item, key) =>
   { name: item.name }
);

This obviously isn't right but I'm not sure how to say that columns needs to be an array of the data in the .map function.这显然是不对的,但我不确定如何说列必须是 .map 函数中的数据数组。

Please help.请帮忙。 Thanks谢谢

Use eval keyword to convert strings to JS expressions使用eval关键字将字符串转换为 JS 表达式

let columns = this.props.columns.map(item =>
   item.options 
    ? ({ ...item, options: eval(item.options) })
    : item
);

But there is one problem though.但是有一个问题。 Babel cannot transpile the output of eval since it's generated in runtime. Babel 无法转译eval的输出,因为它是在运行时生成的。 So you must convert JSX to normal JS expressions that doesn't need transpilation.因此,您必须将 JSX 转换为不需要转译的普通 JS 表达式。

So you code must be like this所以你的代码一定是这样的

const columns = [{
  name: "Actions",
  options: {
    customBodyRender: '(value, tableMeta, updateValue) => { return React.createElement(Options, null); }'
      // or 
    customBodyRender: '(value, tableMeta, updateValue) => { return /*#__PURE__*/_react.default.createElement(Options, null); }'
      // Depends on your babel configurations
}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM