我有一个react-intl软件包问题。我正在使用injectIntl方式在组件中使用道具。纯字符串是可以的,但如果包装HTML标记,它将无法正常工作。
纯字符串成功案例
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.create_button:
// Only create a new thread if it is not created or it is terminated.
if (thread == null || thread.getState() == Thread.State.TERMINATED) {
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
final int finalI = i;
// This will post a message to main/UI thread.
textCounter.post(new Runnable() {
@Override
public void run() {
textCounter.setText(String.valueOf(finalI));
}
});
// Sleep current thread in 0.5 second before running next step.
Thread.sleep(500);
}
// Display Done after finishing counter.
textCounter.post(new Runnable() {
@SuppressLint("SetTextI18n")
@Override
public void run() {
textCounter.setText("Done!");
}
});
} catch (InterruptedException e) {
// Display Cancelled if the current thread is cancelled.
textCounter.post(new Runnable() {
@SuppressLint("SetTextI18n")
@Override
public void run() {
textCounter.setText("Cancelled!");
}
});
}
}
});
} else {
Toast.makeText(MainActivity.this,
"Thread is already created. No need to create anymore.",
Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.start_button:
// Start thread if it is created.
if (thread != null && thread.getState() == Thread.State.NEW) {
thread.start();
} else {
Toast.makeText(MainActivity.this,
"Thread is not created yet or it is running.",
Toast.LENGTH_SHORT)
.show();
}
break;
case R.id.cancel_button:
// Cancel the thread if it is running.
if (thread != null && thread.isAlive()) {
thread.interrupt();
} else {
Toast.makeText(MainActivity.this,
"Thread is not running yet.",
Toast.LENGTH_SHORT)
.show();
}
break;
}
}
};
带有HTML标签失败案例的纯字符串
const _tableNoText = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: basket.table }
);
//console -> Table 1
如果将const _tableNoText = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: <b>basket.table</b> }
);
// console -> Table [object object]
更改为formatMessage
,它将输出与上述相同的结果,我该如何解决?
非常感谢。
答案 0 :(得分:1)
使用{ value: <b>basket.table</b> }
时,实际上是在创建React组件b
,这是一个普通的JavaScript对象。 tsx
(或jsx
)编译器只是向您隐藏了这一步。
因此,如果要呈现HTML,则必须用引号将实际的HTML字符串包装起来,然后翻译该字符串,然后让React将该HTML字符串解包(或将其转换为DOM元素)。
const translated = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: '<strong>STRONG</strong>' }
);
return (
<div dangerouslySetInnerHTML={{__html: translated}} />
)
如果要插值basket.table
,只需将其作为另一个值传递即可:
...
{
value: '<strong>STRONG</strong>',
table: basket.table,
}