如何将Divi自定义模块的PHP变量传递至React JSX?
解决Divi自定义模块中PHP变量传递到React JSX的问题
问题分析
你在Divi自定义模块中尝试将PHP类的myName变量传递到前端React JSX组件,但当前代码无法实现,核心原因:
- 前端JSX错误地试图从
this.state获取数据,而该变量并未被传递到组件的props中 - 后端PHP未将
myName注册为模块的可传递属性,导致前端无法通过Divi的标准机制获取
解决方案
方法一:通过模块字段传递(推荐)
这种方式符合Divi模块的设计规范,变量会自动同步到前端组件的props中。
1. 修改PHP模块代码,添加隐藏字段
在Helloworld.php的get_fields方法里,新增一个隐藏字段存储myName的值:
public function get_fields() { return array( 'content' => array( 'label' => esc_html__('Content', 'fabt-featured-author-book-title'), 'type' => 'tiny_mce', 'option_category' => 'basic_option', 'description' => esc_html__('Content entered here will appear inside the module.', 'fabt-featured-author-book-title'), 'toggle_slug' => 'main_content', ), // 新增隐藏字段传递myName 'my_name' => array( 'type' => 'hidden', 'default' => $this->myName, 'description' => esc_html__('Author name', 'fabt-featured-author-book-title'), ), ); }
2. 修改前端JSX组件,从props读取变量
在Helloworld.jsx中,直接从this.props获取传递过来的my_name:
// External Dependencies import React, { Component } from 'react'; // Internal Dependencies import './style.css'; class HelloWorld extends Component { static slug = 'fabt_hello_world'; render() { const Content = this.props.content; const myName = this.props.my_name; alert(myName); // 测试输出变量值 return ( <div> <h1> <Content/> </h1> <h1>{myName}</h1> </div> ); } } export default HelloWorld;
方法二:通过HTML数据属性传递
如果不想新增模块字段,也可以给渲染的HTML添加data属性,再在JSX中读取:
1. 修改PHP的render方法
public function render($attrs, $content = null, $render_slug) { // 给容器添加data-my-name属性,存储变量值 return sprintf('<div data-my-name="%2$s"><h1>%1$s</h1><h1>%2$s</h1></div>', $this->props['content'], esc_attr($this->myName) // 转义避免XSS风险 ); }
2. 修改JSX组件读取数据属性
// External Dependencies import React, { Component } from 'react'; // Internal Dependencies import './style.css'; class HelloWorld extends Component { static slug = 'fabt_hello_world'; constructor(props) { super(props); this.elRef = React.createRef(); } componentDidMount() { // 通过ref获取DOM元素,读取data属性 const myName = this.elRef.current.dataset.myName; alert(myName); } render() { const Content = this.props.content; return ( <div ref={this.elRef}> <h1> <Content/> </h1> </div> ); } } export default HelloWorld;
注意事项
- 传递变量时务必使用
esc_attr()转义,避免XSS安全漏洞 - Divi可视化构建器模式下,优先使用模块字段传递的方式,更符合官方设计逻辑
内容的提问来源于stack exchange,提问作者Amrith Sudarshan
相关产品推荐
相关产品推荐

