【发布时间】:2016-06-05 17:11:19
【问题描述】:
我目前有从服务器返回的字符串,其中包含需要在前端插入的变量。我正在使用 React 和 Redux 并将字符串设置为组件的 props,以便按如下方式访问它们:
this.props.translations['hello-message']
示例字符串如下所示:
Hello, ${name}!
此外,我还从服务器返回了用户名,并将其设置为 props。如何插入字符串,以便用户名出现在字符串中,从而出现在渲染的 React 组件中。
我尝试在 React 组件的渲染中使用 String.prototype.replace() 方法,如下所示:
let helloMessage = this.props.translations['hello-message'].replace('${name}', 'Joe');
但这会返回错误:“未捕获的类型错误:无法读取未定义的属性‘替换’”。我尝试了各种其他策略,例如 componentWillReceiveProps() 中的函数或创建此处提到的辅助函数:How can I construct a Template String from a regular string? all 无济于事。
【问题讨论】:
标签: javascript string reactjs ecmascript-6