古腾堡并不打算在前端做动态反应。
然而,有一种方法可以绕过这个问题:
我假设在使用npm init @wordpress/block my-block 到init your block.
您必须在中注册自己的客户端脚本my-block.php 在前端执行;一个缺点是:它被加载到每个页面上。
function create_block_my_block_init()
{
    $client_js = \'build/client.js\';
    wp_register_script(
        \'create-block-my-block-client\',
        plugins_url($client_js, __FILE__),
        $script_asset[\'dependencies\'],
        $script_asset[\'version\']
    );
    $client_css = \'build/client.css\';
    wp_register_style(
        \'create-block-my-block-client\',
        plugins_url($client_css, __FILE__),
        array(),
        filemtime("$dir/$client_css")
    );
    ...
    register_block_type(\'create-block/my-block\', array(
        ...
        \'script\' => \'create-block-my-block-client\',
        \'style\'  => \'create-block-my-block-client\', // Override default and import custom scss file.
    ));
}
 请注意,您不能使用
build/style-index.css / 
style.scss 不再使用或使用
register_block_style 为此目的。但最好通过
import \'./custom.scss\'; 在您的React组件中(此处:
MyComponent).
添加webpack.config.js 要加载脚本,请访问根文件夹:
const defaultConfig = require( \'@wordpress/scripts/config/webpack.config\' );
module.exports = {
    ...defaultConfig,
    entry: {
        ...defaultConfig.entry,
        client: \'./src/client.js\',
    },
};
 在中为前端添加HTML包装器
src/save.js 因此,您可以引用脚本:
export default function save() { return (
    <div className="my-block-wrapper"></div>
);}
 请注意,不应将包装器添加到
src/edit.js 由于React组件是动态加载的,因此直接使用那里的自定义组件。
import MyComponent from \'@path_to_node_modules/MyComponent\';
export default function Edit( { className } ) { return (
     <MyComponent/>
);}
 将前端react代码添加到
src/client.js:
import { render } from \'@wordpress/element\';
import MyComponent from \'@path_to_node_modules/MyComponent\';
window.addEventListener(\'DOMContentLoaded\', (event) => {
    const wrappers = document.getElementsByClassName(`my-block-wrapper`);
    for(let wrapper of wrappers) {
        render(<MyComponent/>, wrapper);
    }
});
 查看我的
full example here.
来源1:https://javascriptforwp.com/adding-react-to-a-wordpress-theme-tutorial/
资料来源2:https://stackoverflow.com/questions/51771125/wordpress-gutenberg-react-components-on-front-end
资料来源3:https://www.youtube.com/watch?v=jauZCeLrGFA
如果您有反馈或改进,请随时编辑。