javascript - React 组件,或从类似于 react-intl 的存储数据中替换字符串文字的策略
问题描述
我正在从与此类似的 api 调用中接收数据。
simplified_response: {
variables:{
name: 'John',
age: '25',
gender: 'male',
},
strings:[
'<p>Hello ${name}</p>',
'<p>${name},<br/> I understand you are ${age} years old</p>',
'<p>${name},<br/> I understand you are ${gender}</p>',
},
};
我试图在显示反应之前替换字符串文字。有没有一种类似于 react-intl FormattedMessage 的简单方法?
$
在 react-intl 我认为如果不存在的话你可以做这样的事情
import React from 'react';
import R from 'ramda';
import { FormattedHTMLMessage } from 'react-intl';
export const print = (props) => {
return (
<div>
{ R.map((string) => (
<FormattedHTMLMessage
defaultMessage={ string }
values={ props.response.variables }
/>
), props.response.strings) }
</div>
);
};
Expandable.propTypes = {
response: PropTypes.obj,
};
解决方案
尝试这个:
let { variables, strings } = simplified_response
for (let [key, value] of Object.entries(variables)) {
strings = strings.map(string => string.replace('${' + key + '}', value))
}
simplified_response.strings = strings