reactjs - 带有 React 的 Wordpress 插件中的短代码属性

标签 reactjs wordpress

我试图弄清楚如何将属性传递到 Wordpress 中基于 react 的插件中(使用 @wordpress/scripts)。
我的 main.php 文件:

<?php
defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );

define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );

add_shortcode( 'my_app', 'my_app' );
/**
 * Registers a shortcode that simply displays a placeholder for our React App.
 */
function my_app( $atts = array(), $content = null , $tag = 'my_app' ){
    ob_start();
    ?>
        <div id="app">Loading...</div>
        <?php wp_enqueue_script( 'my-app', plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true ); ?>
    <?php 
    return ob_get_clean();
}
因此,如果我想使用此短代码 [my_app form="login"] 加载应用程序,我该如何将此属性传递给 wp_enqueue_script() ?以及如何在 react 端根据此属性显示内容?如果属性为“注册”,我正在尝试显示注册表
我的 react 主文件:
import axios from 'axios';
const { Component, render } = wp.element;

class WP_App extends Component { 
constructor(props) {
    super(props);
    this.state = { username: '', password: '' };
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

render() {
    return (
        <div class="login">
            <form onSubmit={this.handleSubmit} class="justify-content-center">
            <div class="form-group">
                <label htmlFor="username">
                    Username
                </label>
                <input
                    class="form-control"
                    id="username"
                    onChange={this.handleUsernameChange}
                    value={this.state.username}
                    type="email"
                />
             </div>
            <div class="form-group">
                <label htmlFor="password">
                    Password
                </label>
                <input
                    class="form-control"
                    id="password"
                    onChange={this.handlePasswordChange}
                    value={this.state.password}
                    type="password"
                />
            </div>
            <button class="btn btn-primary">
                Submit
            </button>
            </form>
        </div>
    );
}

handleUsernameChange(e) {
    this.setState({ username: e.target.value });
}

handlePasswordChange(e) {
    this.setState({ password: e.target.value });
}

handleSubmit(e) {
    e.preventDefault();
    if (!this.state.username.length) {
        return;
    }
    if (!this.state.password.length) {
        return;
    }
    const creds = { username: this.state.username,
                    password: this.state.password };
    axios.post('https://example.com:8443/login', creds)
        .then(response => {
                console.log("SUCCESSS")
                window.open('https://example.com/login?t=' + response.data.token, "_blank")  
            }
        )
        .catch(error => {
            if (error.response && error.response.data){
                if (error.response.data === "USER_DISABLED"){
                    console.log("User account disabled."
                    )
                }
                if (error.response.data === "ACCOUNT_LOCKED"){
                    console.log("User account is locked probably due to too many failed login attempts."
                    )
                }
                else{
                    console.log("Login failed."
                    )
                }
            }
            else{
                console.log("Login failed."
                )
                
            }
            console.log(error.response)
        });
}
}


render(
    <WP_App />,
    document.getElementById('app')
);

最佳答案

WordPress 为脚本加载自定义数据的方法是使用 wp_localize_script功能。
顺便说一下,您可以重写您的短代码功能

add_shortcode( 'my_app', 'my_app' );
/**
 * Registers a shortcode that simply displays a placeholder for our React App.
 */
function my_app( $atts = array(), $content = null , $tag = 'my_app' ){
    add_action( 'wp_enqueue_scripts', function() use ($atts) {
        wp_enqueue_script( 'my-app', plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true );
        wp_localize_script(
            'my-app',
            'myAppWpData',
            $atts 
        );
    });

    return '<div id="app">Loading...</div>';
}
然后你可以顺便通过 JavaScript 使用短代码设置对象:
window.myAppWpData['form'] // if you set form as shortcode param
然后你可以将此选项设置为你的 react 的 Prop 参数 WP_App 成分。
然后你可以渲染你的 WP_APP 内容有条件地添加到其短代码参数:
主渲染:
render(
    <WP_App shortcodeSettings={window.myAppWpData} />,
    document.getElementById('app')
);

and how can I display a content according to this attribute in react side?


您可以根据短代码 atts 值使用条件逻辑。
您可以在官方文档页面上找到有关条件 React 逻辑的更多详细信息
https://reactjs.org/docs/conditional-rendering.html
WP_APP 渲染:
你可以用 props.shortcodeSettings WP_APP内render()函数来构建您想要显示组件的任何逻辑。
render() {
    return (
       // you could use props.shortcodeSettings to build any logic
       // ...your code
    )
}
如果您想在页面上有多个短代码。
您可以考虑添加uniqid( 'my-app' )脚本句柄名称
function my_app( $atts = array(), $content = null, $tag = 'my_app' ) {
    $id = uniqid( 'my-app' );
    
    add_action( 'wp_enqueue_scripts', function () use ( $atts, $id ) {
        wp_enqueue_script( "my-app", plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true );
        wp_localize_script(
            "my-app",
            "myAppWpData-$id",
            $atts
        );
    } );

    return sprintf( '<div id="app-%1" data-my-app="%1">Loading...</div>', $id );
}
通过这种方式 - 您可以为您的 index.js 实现多个应用程序的文件逻辑,
const shortcodesApps = document.querySelectorAll('[data-my-app]');

shortcodesApps.forEach((node) => {
    const nodeID = node.getAttribute('data-my-app');
    const shortcodeSettings = window[`myAppWpData-${nodeID}`];

    render(
        <WP_App shortcodeSettings={shortcodeSettings} />,
        node
    );
})

关于reactjs - 带有 React 的 Wordpress 插件中的短代码属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63050614/

相关文章:

javascript - react : Variable after keyname in map function

javascript - 新手 - ReactJS 中的 "class in class"

jquery - 如何缓存外部json请求?

wordpress - WordPress 是否适合年浏览量为 317k 的网站

php - Woocommerce 中特定支付网关结账时的附加字段

php - wp_register_style() 和 wp_enqueue_style 的区别

javascript - React 中的 useState() 是什么?

javascript - React-Strap 的日期选择器

javascript - React 组件未在 History.push 上重新加载

php - the_field ('user' ) 带来所有信息