React的ts文件中通过createElement拼接一段内容出来
比如接口返回一个值
const values = ['¥23.00', '¥40.00/kg'];
想做到如下效果,
如果单纯的用render渲染会很简单,
但是在ts文件中处理,所以采用了createElement拼接
代码如下:
format: (values: string[]) => {
if (!values || !values.length) {
return React.createElement('div', {}, '-');
}
const contents: Array<any> = [];
forEach(values, (value: string, index: number) => {
let content;
const line =
index === 0
? React.createElement(
'span',
{ style: { color: 'red' } },
'-'
)
: null;
if (value.includes('/kg')) {
const [price, kg] = value.split('/');
content = React.createElement('div', {}, [
React.createElement(
'span',
{ style: { color: 'red' } },
price
),
React.createElement('span', {}, '/'),
React.createElement('span', {}, kg),
line,
]);
} else {
content = React.createElement('div', {}, [
React.createElement(
'span',
{ style: { color: 'red' } },
value
),
line,
]);
}
contents.push(content);
});
const div = React.createElement('div', {}, contents);
return div;
},
希望对大家了解createElement有点帮助❤️