首先创建存放Blocks的文件夹,命名为myBlocks或者随便,然后在文件夹里创建banner.js 或者随便,
首先注册Block , 然后通过回调函数执行编辑页面和前端展示页面的操作:
wp.blocks.registerBlockType("ourblocktheme/banner",{
title:"Banner",
edit:EditComponent,
save:SaveComponent
});
function EditComponent() {
return (
<div className="page-banner">
<div className="page-banner__bg-image" style={{backgroundImage:"url('')"}}></div>
<div className="page-banner__content container t-center c-white">
<h1 className="headline headline--large"><?php _e( 'Welcome', 'university' ); ?>!</h1>
<h2 className="headline headline--medium">We think you’ll like it here.</h2>
<h3 className="headline headline--small">Why don’t you check out the <strong>major</strong> you’re interested in?</h3>
<a href="#" className="btn btn--large btn--blue">Find Your Major</a>
</div>
</div>
)
}
function SaveComponent() {
return <p>This is from our block<p/> }
react 解析的脚本用的wordpress自带的脚本:操作方法如下:
安装好之后,修改package.json 里面的scripts命令
"scripts": {
"start": "wp-scripts start src/index.js blocks/banner.js",
"dev": "wp-scripts start -w",
"devFast": "wp-scripts start",
"test": "echo \"Error: no test specified\" && exit 1"
},
转移的话复制package.json到新项目就好,然后执行:
npm install
就可以安装全部的scripts.
当安装结束之后,就可以运行start命令:
npm run start
当命令结束时候,你就会发现在build文件夹出现一个banner.js文件。这表明已经把jsx解析成了js文件。现在只需要注册自定义的Block 来使用这个js文件。
打开functions.php, 注册:
先注册scripts后注册blocktype.
add_action( 'init', 'bannerBlock' );
function bannerBlock() {
//先注册script然后注册block
wp_register_script( 'bannerBlockScript',get_stylesheet_directory_uri() . '/build/banner.js',array('wp-blocks','wp-editor') );
register_block_type("blocktheme/banner",array(
'editor_script' => 'bannerBlockScript'
));
}