如何将翻译 __() 与超链接一起使用

mic*_*cky 13 javascript php wordpress jsx reactjs

在 WordPress 中创建块时,我需要添加带有链接的翻译。我在 JS 中这样做,但它没有提供预期的结果:

import { render } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

export default function Final() {

    let d = <a href="https://example.com">bothered me.</a>;

    return (

        <p>  { __( 'The cold never {d} anyway.', 'text-domain' ) } </p>

    )
}

document.addEventListener( "DOMContentLoaded", function(event) {
    const appRoot = document.getElementById( 'root' );

    if ( appRoot ) {
        render(
            <Final/>,
            appRoot
        )
    }
});
Run Code Online (Sandbox Code Playgroud)

在 PHP 中,我可以使用 sprintf 并使用 %1s 等占位符轻松做到这一点。

echo sprintf(
    __( 'The cold never %1s anyway', 'text-domain' ),
    '<a href="https://example.com">bothered me.</a>'
);
Run Code Online (Sandbox Code Playgroud)

在 React 中创建块时,如何执行与 sprintf 等效的操作?

New*_*bie 3

您正在尝试使用 React 在翻译的句子中插入 html 标签。您需要保留一个占位符(类似{0}),然后需要将其替换为实际组件。

当使用 PHP 时,您只需用其他文本(即 HTML)替换文本,而在 React 中,您正在使用组件,因此您不能简单地替换它们。

export default function Final() {
    const [before, after] = __('The cold never {0} anyway.', 'text-domain').split('{0}');
    
    return (<p>
        { before }
        <a href="https://example.com">bothered me.</a>
        { after }
    </p>);
}
Run Code Online (Sandbox Code Playgroud)

边注

'The cold never {d} anyway.'是一个纯字符串,也许是您想要的`The cold never ${d} anyway.`(用于字符串模板)。