WordPress React開發專案初學者指南

WordPress React開發專案初學者指南

WordPress是一個功能強大的內容管理系統 (CMS),可讓您構建從簡單網站到複雜複雜的電子商務商店的所有內容。要將平臺的PHP程式碼與JavaScript整合,您可以利用WP REST API和WordPress React

React由Facebook開發,是一個使用者介面 (UI)庫,它使用一種簡單的、基於元件的方法來構建易於理解的可擴充套件、跨平臺的應用程式。但是,重要的是要學習如何正確使用它以充分利用其特性和功能。

在本指南中,我們將解釋如何在WordPress中使用React。我們將討論什麼是框架,概述它的好處,並向您展示如何使用它。

React簡介

在開始之前,我們首先要問一個問題,“什麼是React?” . 也稱為 ReactJS,它是可用於Web開發的最流行的JavaScript庫之一。

React官網

它由Facebook建立和維護,包含大量可用於構建UI元件的JavaScript程式碼片段。

與流行的看法相反,ReactJS不是一個JavaScript框架,因為它只呈現應用程式檢視層的元件。因此,如果您正在尋找更復雜的功能,可以將其與Vue.js等實際框架配對。

同樣重要的是要注意有ReactJS和React Native。後者是基於React庫構建的開源JavaScript框架。您可以使用它為iOS和Android建立跨平臺應用程式和特定於平臺的元件。

React特性和功能

要了解React的好處,瞭解它的工作原理會很有幫助。以下是它的一些最重要的特性和功能:

JSX

React中使用的主要JavaScript語法擴充套件是JSX。您可以使用它在JavaScript物件中嵌入HTML程式碼並簡化複雜的程式碼結構。

JSX還通過使第三方難以通過未明確寫入應用程式的使用者輸入注入額外程式碼來幫助防止跨站點指令碼 (XSS) 攻擊。

JSX標記包括名稱、子項和屬性。一個典型的HTML影象標籤看起來像這樣:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
< img class = "" src= "" alt= "" >
< img class = "" src= "" alt= "" >
< img class = "" src= "" alt= "" >

但是,一個JSX標記應該如下所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
< img className= "" src= "" alt= "" / >
< img className= "" src= "" alt= "" / >
< img className= "" src= "" alt= "" / >

此外,數值寫在大括號內。與JavaScript類似,引號代表字串:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const name = 'John Doe’;
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
const name = 'John Doe’; const element = <h1>Hello, {name}</h1>; ReactDOM.render( element, document.getElementById('root') );
const name = 'John Doe’;
const element = <h1>Hello, {name}</h1>;
ReactDOM.render(
  element,
  document.getElementById('root')
);

您可以將任何有效的JavaScript表示式放在大括號內。例如,它可以是“user.firstName”或“formatName(user)”。

虛擬DOM

文件物件模型 (DOM)以資料樹結構呈現網頁,React將其儲存在其記憶體中。React可以實現對樹的某些部分的更新,而不是完全重新渲染它。

Virtual DOM提供單向資料繫結。這使得操作和更新它比原始DOM更快。

它使用稱為差異的過程。這是React生成一個新的Virtual DOM樹,將其與舊的比較,然後找到將更改應用到真實 DOM 的最有效方法的時候。這需要更少的時間和更少的資源,這對於涉及大量使用者互動的大型專案是有益的。

DOM還支援宣告式API。這意味著您可以告訴React您希望UI處於哪種狀態,以確保DOM將匹配該狀態。

元件

正如我們所提到的,React元件是構成UI的獨立、可重用的程式碼片段。這些元件的工作方式類似於JavaScript函式。他們接受道具,這是任意輸入。當一個函式元件返回一個元素時,它會影響UI的外觀。

Props是隻讀的。這是一個例子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
const ParentComponent = () => {
const [stateVariable, setStateVariable] = useState('this is the starting value for the variable');
return (
<div>
<h1>This is a function component view</h1>
<ChildComponent exampleProp={stateVariable} />
</div>
)
}
const ChildComponent = (props) => {
return (
<div>
<h2>{props.exampleProp}</h2>
</div>
)
}
ReactDOM.render( <ParentComponent />, document.getElementById('app') );
import React, { useState } from 'react' import ReactDOM from 'react-dom' const ParentComponent = () => { const [stateVariable, setStateVariable] = useState('this is the starting value for the variable'); return ( <div> <h1>This is a function component view</h1> <ChildComponent exampleProp={stateVariable} /> </div> ) } const ChildComponent = (props) => { return ( <div> <h2>{props.exampleProp}</h2> </div> ) } ReactDOM.render( <ParentComponent />, document.getElementById('app') );
import React, { useState } from 'react' 
import ReactDOM from 'react-dom' 
 
const ParentComponent = () => { 
    const [stateVariable, setStateVariable] = useState('this is the starting value for the variable'); 
 
    return ( 
        <div> 
            <h1>This is a function component view</h1>
            <ChildComponent exampleProp={stateVariable} />
        </div> 
    ) 
} 
 
const ChildComponent = (props) => {
    return (
        <div>
            <h2>{props.exampleProp}</h2>
        </div>
    )
}
 
 
ReactDOM.render( <ParentComponent />, document.getElementById('app') );

有兩種主要型別——元件函式元件。類元件使用生命週期WordPress鉤子和API呼叫:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
return (
<div>
<h1>This is a view created by a class component</h1>
</div>
);
}
}
class ExampleComponent extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div> <h1>This is a view created by a class component</h1> </div> ); } }
class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { };
  }
  render() {
    return (
      <div>
        <h1>This is a view created by a class component</h1>
      </div>
    );
  }
}

同時,一個功能元件看起來像下面的例子:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const ExampleComponent = (props) => {
const [stateVariable, setStateVariable] = useState('');
return (
<div>
<h1>This is a function component view</h1>
</div>
)
}
const ExampleComponent = (props) => { const [stateVariable, setStateVariable] = useState(''); return ( <div> <h1>This is a function component view</h1> </div> ) }
const ExampleComponent = (props) => {
    const [stateVariable, setStateVariable] = useState('');
    return (
        <div>
            <h1>This is a function component view</h1>
        </div>
    )
}

功能元件用於在沒有資料請求或狀態管理的情況下呈現檢視。

狀態

State指的是React元件的內建物件。這是您儲存元素屬性值的地方。如果狀態改變,元件會重新渲染。

狀態管理是管理這些應用程式狀態並將資料儲存在狀態管理庫中的過程。你可以使用一些狀態管理庫,包括ReduxRecoil,後者對初學者更友好。

為什麼要使用React?

使用React進行WordPress開發有很多好處。對於初學者來說,它對初學者很友好,許多網路託管服務提供商都支援它的使用。

由於它依賴於純JavaScript和元件,因此您只需學習幾天即可使用它來建立基於Web的應用程式。還有很多網站可以學習如何免費線上編碼。對JavaScript基礎知識的紮實理解可以簡化該過程。

React的另一個好處是它允許您在其他應用程式中重用元件。它是開源的,因此您可以預先構建您的元件並將它們巢狀在其他元件之間,而不會使您的程式碼臃腫。

由於JSX整合,React元件的編寫也相對簡單,我們稍後會討論。您可以合併HTML排版、標籤並利用多種功能呈現來進行動態應用程式開發。

藉助React,您還可以使用官方命令列介面 (CLI) – Create React App – 來加快單頁應用程式的開發。它帶有預配置的工具,可以幫助您簡化設定和學習過程。

最後,React也是SEO友好的。虛擬DOM實現有助於提高頁面速度、提高效能和伺服器端渲染,使機器人更容易抓取您的網站。

WP REST API概述

WordPress REST應用程式介面 (API)使開發人員能夠將JavaScript框架(例如React)與WordPress整合。您可以從站點的前端訪問WP REST API,新增自定義文章型別,並構建由該API支援的React應用程式。

WP REST API是一組用於構建軟體應用程式的協議。它們定義了程式之間如何共享資訊和資料以及它們的元件如何互動。REST是Representational State Transfer的縮寫,指的是程式的風格定義架構約束。

應用程式讀取的結構化資料格式稱為JavaScript Object Notation (JSON)。它有助於簡化WordPress與其他應用程式和程式之間的通訊。

WP REST API產生了一個解耦環境,允許使用者將WordPress視為無頭CMS。這意味著可以使用多種前端框架來鉤住WordPress的後端。這對於不太熱衷於PHP的開發人員來說是有利的。

React——開始之前

JavaScript、CSS和HTML的基本知識將有助於學習React。此外,如果您熟悉ECMAScript 6(也稱為 ES6)、函數語言程式設計和麵向物件程式設計,學習過程會更加高效。

在程式方面,您還需要在計算機上安裝一些依賴項。這包括NodeJSnpm以及一個文字編輯器。或者,您可能還想使用Git進行版本控制。

為WordPress開發React專案最流行的方法是使用Create React App

Create React App

CRA提供了一個簡單的環境來學習React並使用它來構建單頁應用程式。請注意,為了使用它,您首先需要在您的裝置上安裝Node和npm。

要建立一個新專案,您可以在終端中執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app wp-react-demo
npx create-react-app wp-react-demo
npx create-react-app wp-react-demo

如果您還沒有這樣做,它將確認您要在建立演示之前安裝Create React App。這使樣板模板。你也可以用你自己的名字替換“wp-react-demo”。

接下來,執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd wp-react-demo
npm start
cd wp-react-demo npm start
cd wp-react-demo
npm start

目錄結構將如下所示:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── registerServiceWorker.js
├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── registerServiceWorker.js
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── registerServiceWorker.js

在src目錄中,您將找到您將要處理的所有JavaScript檔案。現在,您可以訪問localhost:3000來載入index.html檔案。

public/index.html檔案不包含太多內容。但是,您可以找到以下行,這將是您專案的起點:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div id="root"></div>
<div id="root"></div>
<div id="root"></div>

在src目錄的index.js檔案下,您會發現以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
 
ReactDOM.render(<App />, document.getElementById('root'));

這意味著它正在渲染App元件,您可以在src./App.js下找到該元件。您可以將其替換為您自己的HTML內容。我們可以使用JSX語法擴充套件HTML Insider  render()

如何從React查詢WP REST API

預設情況下,您可以建立一個GET請求在您網站的前端使用WP REST API。例如,您可以使用/wp-json/wp/v2/posts獲取您的所有文章。堅持前面的例子,這個文章資料將位於http://localhost/wp-json/wp/v2/posts/

要開始使用React,您可以在終端中執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app react-app
npx create-react-app react-app
npx create-react-app react-app

然後,執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd react-app
npm install @material-ui/core
cd react-app npm install @material-ui/core
cd react-app 
npm install @material-ui/core

接下來,您可以輸入以下示例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useEffect, useState } from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
export default function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
async function loadPosts() {
const response = await fetch('/wp-json/wp/v2/posts');
if(!response.ok) {
// oups! something went wrong
return;
}
const posts = await response.json();
setPosts(posts);
}
loadPosts();
}, [])
return (
<Grid container spacing={2}>
{posts.map((post, index) => (
<Grid item xs={4} key={index}>
<Card>
<CardContent>
<Typography
color="textSecondary"
gutterBottom
dangerouslySetInnerHTML={{__html: post.title.rendered}} />
<Typography
variant="body2"
component="p"
dangerouslySetInnerHTML={{__html: post.content.rendered}} />
</CardContent>
</Card>
</Grid>
))}
</Grid>
);
}
import React, { useEffect, useState } from 'react'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; export default function Posts() { const [posts, setPosts] = useState([]); useEffect(() => { async function loadPosts() { const response = await fetch('/wp-json/wp/v2/posts'); if(!response.ok) { // oups! something went wrong return; } const posts = await response.json(); setPosts(posts); } loadPosts(); }, []) return ( <Grid container spacing={2}> {posts.map((post, index) => ( <Grid item xs={4} key={index}> <Card> <CardContent> <Typography color="textSecondary" gutterBottom dangerouslySetInnerHTML={{__html: post.title.rendered}} /> <Typography variant="body2" component="p" dangerouslySetInnerHTML={{__html: post.content.rendered}} /> </CardContent> </Card> </Grid> ))} </Grid> ); }
import React, { useEffect, useState } from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
    
export default function Posts() {
    const [posts, setPosts] = useState([]);
    useEffect(() => {
        async function loadPosts() {
            const response = await fetch('/wp-json/wp/v2/posts');
            if(!response.ok) {
                // oups! something went wrong
                return;
            }
    
            const posts = await response.json();
            setPosts(posts);
        }
    
        loadPosts();
   }, [])
  return (
    <Grid container spacing={2}>
      {posts.map((post, index) => (
      <Grid item xs={4} key={index}>
        <Card>
           <CardContent>
                <Typography
                    color="textSecondary"
                    gutterBottom
                    dangerouslySetInnerHTML={{__html: post.title.rendered}} />
                <Typography
                    variant="body2"
                    component="p"
                    dangerouslySetInnerHTML={{__html: post.content.rendered}} />
            </CardContent>
        </Card>
      </Grid>
     ))}
    </Grid>
 );
}

上面的例子使用了React HooksuseEffectuseState. 前者宣告文章陣列並呼叫更新它,而後者獲取程式碼。

如何使用React建立自定義文章型別

您還可以使用React建立WordPress自定義文章型別。但是,您需要提前安裝一些工具。這將有助於使流程儘可能無縫和簡單。

首先,您需要新增WordPres外掛Custom Post Type UI

Custom Post Type UI

這個外掛簡化了在WordPress中建立自定義文章型別的過程。

我們還建議安裝Advanced Custom Fields (ACF)

Advanced Custom Fields (ACF)

這也是一個免費工具。該外掛可用於建立自定義欄位並將其新增到您的自定義文章型別。我們還建議將ACF安裝到REST API以使您的自定義欄位可用於您的文章型別。

要開始,請從您的管理區域導航到CPT UI > Add/Edit Post Types。在我們的示例中,我們將使用名稱“Books”。我們還將選擇自動填充其餘欄位的選項。

CPT UI新增編輯文章型別

Show in REST API部分下,將其設定為True並輸入“Books”作為REST API基礎slug。在Supports下,選中Author Custom fields覈取方塊。完成後單擊儲存文章型別

接下來,我們可以為自定義文章型別建立自定義欄位。導航到Custom Fields > Add New,然後輸入適當的標題,例如“Book Info”。您可以單擊新增欄位, 然後填寫欄位標籤、名稱和型別。

ACF新增欄位

Location下,您可以將文章型別設定為與圖書自定義文章型別相同。完成後,選擇釋出以啟用自定義欄位。

接下來,轉到我的圖書 > 新增新書 並輸入其標題、摘要和特色圖片。您可以重複此過程以建立任意數量的內容。

現在,從您的終端輸入以下命令,執行每個命令,然後繼續執行下一個命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app frontend
cd frontend
npm i axios
npm start
npx create-react-app frontend cd frontend npm i axios npm start
npx create-react-app frontend
cd frontend
npm i axios
npm start

接下來,在src目錄,您可以建立一個名為components的資料夾,然後建立一個名為books.js的檔案。完成後,輸入以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { Component } from 'react';
import axios from 'axios';
export class Books extends Component {
state = {
books: [],
isLoaded: false
}
componentDidMount () {
axios.get('http://localhost:3000/wp-json/wp/v2/books')
.then(res => this.setState({
books: res.data,
isLoaded: true
}))
.catch(err => console.log(err))
}
render() {
console.log(this.state);
return (
<div>
</div>
)
}
}
export default Books;
import React, { Component } from 'react'; import axios from 'axios'; export class Books extends Component { state = { books: [], isLoaded: false } componentDidMount () { axios.get('http://localhost:3000/wp-json/wp/v2/books') .then(res => this.setState({ books: res.data, isLoaded: true })) .catch(err => console.log(err)) } render() { console.log(this.state); return ( <div> </div> ) } } export default Books;
import React, { Component } from 'react';
import axios from 'axios';
export class Books extends Component {
   state = {
       books: [],
       isLoaded: false
   }
 componentDidMount () {
   axios.get('http://localhost:3000/wp-json/wp/v2/books')
       .then(res => this.setState({
           books: res.data,
           isLoaded: true
       }))
       .catch(err => console.log(err))
   }
   render() {
      console.log(this.state);
       return (
           <div>
             
           </div>
       )
   }
}
export default Books;

App.js檔案中,輸入以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React from 'react';
import './App.css';
import Books from './components/Books';
function App() {
return (
<div className="App">
<Books>
</div>
);
}
export default App;
import React from 'react'; import './App.css'; import Books from './components/Books'; function App() { return ( <div className="App"> <Books> </div> ); } export default App;
import React from 'react';
import './App.css';
import Books from './components/Books';
function App() {
 return (
   <div className="App">
    <Books>
   </div>
 );
}
export default App;

現在,在您的終端中,您可以執行npm start命令。這將啟動React應用程式。當您在瀏覽器中開啟“Book”資料控制檯時,您可以檢視它。您可以通過對映每本書來顯示每個標題。

Book.js中,輸入以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
render() {
const {books, isLoaded} = this.state;
return (
<div>
{books.map(book => <h4>{book.title.rendered}</h4>)}
</div>
)
}
render() { const {books, isLoaded} = this.state; return ( <div> {books.map(book => <h4>{book.title.rendered}</h4>)} </div> ) }
render() {
      const {books, isLoaded} = this.state;
       return (
           <div>
              {books.map(book => <h4>{book.title.rendered}</h4>)}
           </div>
       )
   }

請注意,您還可以將書籍集合分離為單個書籍元件。您可以通過在src/components其中建立一個檔案來做到這一點. 您還可以新增自定義CSS來設定自定義文章型別 (app.css) 的樣式。

如何建立React WordPress主題(2 種方法)

也許您想知道如何使用React建立WordPress主題。有幾個選項,讓我們看一下兩種流行的方法:

1. 使用WP指令碼建立一個React WordPress主題

在典型的React應用程式中,您需要在檔案頂部匯入React。然而,從WordPress 5.0開始,CMS附帶React和ReactDOM庫並將它們匯出到wp.element,一個全域性視窗物件。

如果您以前使用過React,那麼您可能已經使用過Create React App來執行您的開發伺服器。但是,對於WordPress,這不是必需的。

WordPress團隊基於react-scripts使用Create React App建立了一個wp-scripts包。WP Scripts預設包含命令。

要在主題中載入React,請導航到主題的functions.php檔案,然後新增以下程式碼片段:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Enqueue Theme JS w React Dependency
add_action( 'wp_enqueue_scripts', 'my_enqueue_theme_js' );
function my_enqueue_theme_js() {
wp_enqueue_script(
'my-theme-frontend',
get_stylesheet_directory_uri() . '/build/index.js',
['wp-element'],
time(), // Change this to null for production
true
);
}
// Enqueue Theme JS w React Dependency add_action( 'wp_enqueue_scripts', 'my_enqueue_theme_js' ); function my_enqueue_theme_js() { wp_enqueue_script( 'my-theme-frontend', get_stylesheet_directory_uri() . '/build/index.js', ['wp-element'], time(), // Change this to null for production true ); }
// Enqueue Theme JS w React Dependency
add_action( 'wp_enqueue_scripts', 'my_enqueue_theme_js' );
function my_enqueue_theme_js() {
  wp_enqueue_script(
    'my-theme-frontend',
    get_stylesheet_directory_uri() . '/build/index.js',
    ['wp-element'],
    time(), // Change this to null for production
    true
  );
}

這將新增wp-element作為JavaScript檔案的依賴項。接下來,我們需要設定一個package.json檔案。從WordPress主題的根目錄執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm init
npm init
npm init

完成後,執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install @wordpress/scripts --save-dev
npm install @wordpress/scripts --save-dev
npm install @wordpress/scripts --save-dev

WP指令碼將被下載到您的node_modules中,因此它們可以在您的命令列中使用。要將WP指令碼對映到NPM指令碼,您可以瀏覽到您的package.json檔案,載入“指令碼”設定,並將它們替換為以下示例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"name": "myreacttheme",
"version": "1.0.0",
"description": "My WordPress theme with React",
"main": "src/index.js",
"dependencies": {},
"devDependencies": {
"@wordpress/scripts": "^5.1.0"
},
"scripts": {
"build": "wp-scripts build",
"check-engines": "wp-scripts check-engines",
"check-licenses": "wp-scripts check-licenses",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"start": "wp-scripts start",
"test:e2e": "wp-scripts test-e2e",
"test:unit": "wp-scripts test-unit-js"
},
"author": "",
"license": "1 GNU V2+, MIT"
}
{ "name": "myreacttheme", "version": "1.0.0", "description": "My WordPress theme with React", "main": "src/index.js", "dependencies": {}, "devDependencies": { "@wordpress/scripts": "^5.1.0" }, "scripts": { "build": "wp-scripts build", "check-engines": "wp-scripts check-engines", "check-licenses": "wp-scripts check-licenses", "lint:css": "wp-scripts lint-style", "lint:js": "wp-scripts lint-js", "lint:pkg-json": "wp-scripts lint-pkg-json", "start": "wp-scripts start", "test:e2e": "wp-scripts test-e2e", "test:unit": "wp-scripts test-unit-js" }, "author": "", "license": "1 GNU V2+, MIT" }
{
  "name": "myreacttheme",
  "version": "1.0.0",
  "description": "My WordPress theme with React",
  "main": "src/index.js",
  "dependencies": {},
  "devDependencies": {
    "@wordpress/scripts": "^5.1.0"
  },
  "scripts": {
    "build": "wp-scripts build",
    "check-engines": "wp-scripts check-engines",
    "check-licenses": "wp-scripts check-licenses",
    "lint:css": "wp-scripts lint-style",
    "lint:js": "wp-scripts lint-js",
    "lint:pkg-json": "wp-scripts lint-pkg-json",
    "start": "wp-scripts start",
    "test:e2e": "wp-scripts test-e2e",
    "test:unit": "wp-scripts test-unit-js"
  },
  "author": "",
  "license": "1 GNU V2+, MIT"
}

接下來,您可以執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm start
npm start
npm start

這將查詢從src/index.js匯入的檔案,並在檔案更改時將 它們構建到build/index.js 。

2. 使用Create-React-WPTheme建立一個React WordPress主題

另一種選擇是使用devloco的create-react-wptheme。這個包類似於create-react-app。但是,它使用WordPress而不是webpack作為開發伺服器。您還可以訪問所有核心函式、鉤子、動作、過濾器等。

要進行設定,您可以在本地WordPress安裝中啟動終端(或git bash),然後鍵入以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-wptheme barebones
npx create-react-wptheme barebones
npx create-react-wptheme barebones

“準系統”是主題的名稱。您可以將其更改為您想要呼叫主題的任何內容。

您將看到一條訊息,通知您安裝在其中建立了一個根資料夾和一個“react-src”目錄。這個目錄很重要,因為它將包含您的未編譯程式碼。

接下來,我們需要新增styles.css index.php 其他必要的檔案來驗證它。在終端中,輸入以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd barebones/react-src
npm run wpstart
cd barebones/react-src npm run wpstart
cd barebones/react-src
npm run wpstart

現在,當您導航到wp-admin > Themes時,您應該會看到您的新主題。單擊啟用按鈕,然後返回終端並執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run wpstart
npm run wpstart
npm run wpstart

這應該會自動開啟一個新的瀏覽器選項卡。請注意,不應編輯位於根資料夾中的檔案(react-src 之外的任何內容)。它們包含WordPress和React所需程式碼的編譯版本。

要建立新主題,您可以使用以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-wptheme my_react_theme
npx create-react-wptheme my_react_theme
npx create-react-wptheme my_react_theme

您可以根據需要更改“my_react_theme”。接下來,您可以輸入以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd my_react_theme/react-src
npm run start
cd my_react_theme/react-src npm run start
cd my_react_theme/react-src
npm run start

請記住將其替換為您在上一步中使用的相同名稱。這將設定要在管理區域中檢視的主題。

完成主題開發後,您需要使用build命令將其移至生產環境。為此,請開啟命令提示符,導航到主題的react-src資料夾,然後執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm run build
npm run build
npm run build

這將優化位於資料夾中的檔案。然後,您可以將其部署在您的伺服器上。

如何將React新增到自定義頁面模板

如果您想知道如何使用React建立WordPress子主題,則該過程相對相似。您可以將React新增到自定義頁面模板。

讓我們從一個標準的主題結構開始:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/build
/src
/-- index.js
functions.php
package.json
page-react.php
style.css
/build /src /-- index.js functions.php package.json page-react.php style.css
/build
/src
/-- index.js
functions.php
package.json
page-react.php
style.css

接下來,您將以下程式碼新增到主題的functions.php檔案中:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'twentytwenty-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
[ $parent_style ],
time() //For production use wp_get_theme()->get('Version')
);
wp_enqueue_script(
'my-theme-frontend',
get_stylesheet_directory_uri() . '/build/index.js',
['wp-element'],
time() //For production use wp_get_theme()->get('Version')
);
}
<?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'twentytwenty-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', [ $parent_style ], time() //For production use wp_get_theme()->get('Version') ); wp_enqueue_script( 'my-theme-frontend', get_stylesheet_directory_uri() . '/build/index.js', ['wp-element'], time() //For production use wp_get_theme()->get('Version') ); }
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
 
  $parent_style = 'twentytwenty-style'; 
    
  wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    
  wp_enqueue_style( 'child-style',
    get_stylesheet_directory_uri() . '/style.css',
    [ $parent_style ],
    time() //For production use wp_get_theme()->get('Version')
  );
  wp_enqueue_script(
    'my-theme-frontend',
    get_stylesheet_directory_uri() . '/build/index.js',
    ['wp-element'],
    time() //For production use wp_get_theme()->get('Version')        
  );
  
}

您還需要將程式碼新增到您的style.css檔案中。在其中,複製並貼上以下內容:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/*
Theme Name: Twenty Twenty Child
Description: Twenty Twenty Child Theme
Author: Your Name
Author URI: https://yourwebsite.com
Template: twentytwenty
Version: 0.9.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: twentytwentychild
*/
/* Theme Name: Twenty Twenty Child Description: Twenty Twenty Child Theme Author: Your Name Author URI: https://yourwebsite.com Template: twentytwenty Version: 0.9.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: twentytwentychild */
/*
 Theme Name:   Twenty Twenty Child
 Description:  Twenty Twenty Child Theme
 Author:       Your Name
 Author URI:   https://yourwebsite.com
 Template:     twentytwenty
 Version:      0.9.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Text Domain:  twentytwentychild
*/

接下來,您可以使用此示例建立一個基本的自定義頁面模板page-react.php

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<? php
/**
* Template Name: React Template
*/
get_header();
?>
<main id="site-content" role="main">
<article class="post-2 page type-page status-publish hentry">
<?php get_template_part( 'template-parts/entry-header' ); ?>
<div class="post-inner thin">
<div class="entry-content">
<div id="react-app"></div><!-- #react-app -->
</div><!-- .entry-content -->
</div><!-- .post-inner -->
</article><!-- .post -->
</main><!-- #site-content -->
<?php get_template_part( 'template-parts/footer-menus-widgets' ); ?>
<?php get_footer(); ?>
<? php /** * Template Name: React Template */ get_header(); ?> <main id="site-content" role="main"> <article class="post-2 page type-page status-publish hentry"> <?php get_template_part( 'template-parts/entry-header' ); ?> <div class="post-inner thin"> <div class="entry-content"> <div id="react-app"></div><!-- #react-app --> </div><!-- .entry-content --> </div><!-- .post-inner --> </article><!-- .post --> </main><!-- #site-content --> <?php get_template_part( 'template-parts/footer-menus-widgets' ); ?> <?php get_footer(); ?>
<? php
/**
 * Template Name: React Template
 */
get_header();
?>
<main id="site-content" role="main">
  <article class="post-2 page type-page status-publish hentry">
    <?php get_template_part( 'template-parts/entry-header' ); ?>
    <div class="post-inner thin">
      <div class="entry-content">        
        <div id="react-app"></div><!-- #react-app -->
      </div><!-- .entry-content -->
    </div><!-- .post-inner -->
  </article><!-- .post -->
</main><!-- #site-content -->
<?php get_template_part( 'template-parts/footer-menus-widgets' ); ?>
<?php get_footer(); ?>

您現在可以在WordPress中建立一個新頁面,然後選擇React Template作為頁面模板。

如何在你的應用中使用React

如果您想在現有應用程式中使用React,您可以將其內容交付網路 (CDN)直接新增到您的HTML檔案中。要開始,請導航到要新增React的HTML頁面以開始。

插入一個空格<div>標籤。這將建立一個容器,您可以在其中渲染元件。對於此示例,假設我們正在嘗試建立一個按鈕。

接下來在頁面的閉合標籤</body>前插入三個<script>。前兩個將用於載入 React,第三個將用於載入您的元件程式碼。

現在,在與您的HTML頁面相同的資料夾中,建立一個新檔案並將其命名為button.js(或任何與您要新增的元素相關的名稱)。在該檔案中,複製並貼上以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'use strict';
const e = React.createElement;
class Button extends React.Component {
constructor(props) {
super(props);
this.state = { clicked: false };
}
render() {
if (this.state.clicked) {
return 'You pressed this button.';
}
return e(
'button',
{ onClick: () => this.setState({ clicked: true }) },
'Press Me'
);
}
}
'use strict'; const e = React.createElement; class Button extends React.Component { constructor(props) { super(props); this.state = { clicked: false }; } render() { if (this.state.clicked) { return 'You pressed this button.'; } return e( 'button', { onClick: () => this.setState({ clicked: true }) }, 'Press Me' ); } }
'use strict';
const e = React.createElement;
class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = { clicked: false };
  }
  render() {
    if (this.state.clicked) {
      return 'You pressed this button.';
    }
    return e(
      'button',
      { onClick: () => this.setState({ clicked: true }) },
      'Press Me'
    );
  }
}

這將構建一個按鈕元件,一旦單擊它就會顯示一條訊息。要在 HTML 頁面中使用按鈕,您可以將以下程式碼片段新增到button.js檔案的底部:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const domContainer = document.querySelector('#button_container');
ReactDOM.render(e(Button), domContainer);
const domContainer = document.querySelector('#button_container'); ReactDOM.render(e(Button), domContainer);
const domContainer = document.querySelector('#button_container');
ReactDOM.render(e(Button), domContainer);

這回撥到您新增到HTML頁面的容器<div>。然後它渲染React按鈕元件。

你也可以使用React從頭開始​​建立一個空白的React應用程式。最好的方法是使用我們之前討論過的Create React App解決方案。它對單頁應用程式很有幫助。

首先,您可以在終端中執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app my-app
npx create-react-app my-app
npx create-react-app my-app

請注意,您可以將“my-app”更改為您想要命名的任何名稱。要執行它,您可以通過執行cd my-app命令,然後執行npm start.

然後應用程式將在開發模式下執行。您可以在瀏覽器中的http://localhost:3000檢視它。

小結

即使您是初學者,開發WordPress React專案也可以是一個簡單、直接的過程。但是,重要的是要了解JavaScript框架如何與CMS及其REST API一起工作才能成功。

幸運的是,只要對JavaScript、HTML和CSS有基本的瞭解,您就可以立即學習React。正如我們在這篇文章中所討論的,您可以使用它來建立單頁應用程式和主題以及自定義頁面模板。

我們希望本指南能幫助您更好地瞭解React及其在Web開發方面的功能。

評論留言