擴充現有欄位
如要擴充現有欄位,您必須將內建欄位的子類別 (例如
FieldTextInput
、FieldColour
),然後根據自身需求修改部分內容。
以下列舉幾個可修改的欄位:
如果您要建立
自訂欄位
任何內建欄位皆不需要行為,應將 Field
設為子類別。
常見擴充功能
大多數的自訂欄位會擴充以下三種類型的其中一種:
- 文字輸入:如果您希望使用者能夠在欄位中輸入文字,建議您擴充
FieldTextInput
。
- 數字:如要儲存數字,請擴充
FieldNumber
。
- 下拉式選單:如要建立下拉式選單,但想儲存其他模式,
非預設字串或圖片模型,您必須擴充
FieldDropdown
。
- 注意:擴充
FieldDropdown
之前,請先檢查下拉式選單欄位的
不過,自訂選項不符合您的需求。
在某些情況下,您可能會想要擴充不同的欄位類型。適用對象
範例 FieldLabelSerializable
擴充 FieldLabel
。
子類別
import * as Blockly from 'blockly';
export class MyCustomTextField extends Blockly.FieldTextInput {
constructor(value, validator, config) {
super(value, validator, config);
}
}
欄位子類別的建構函式看起來與 建構函式的建構函式十分相似
自訂欄位。子建構函式的簽名
通常會與超建構函式的簽名相符。
JSON 與登錄
您也應該註冊欄位一次:
Blockly.fieldRegistry.register('my_custom_text_field', MyCustomTextField);
並在類別中提供 fromJson
實作,以便與其搭配運作
JSON 格式:
static fromJson(options) {
const value = Blockly.utils.parsing.replaceMessageReferences(options.value);
return new MySubclassName(value);
}
如要進一步瞭解如何註冊欄位,請參閱 JSON 和註冊
部分。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2024-09-08 (世界標準時間)。
[null,null,["上次更新時間:2024-09-08 (世界標準時間)。"],[[["To extend an existing Blockly field, subclass a built-in field like `FieldTextInput` or `FieldColour` and modify its editor, on-block display, or displayed text."],["For custom fields with unique behaviors, subclass the base `Field` class instead of extending an existing field."],["Common field extensions involve customizing text input (`FieldTextInput`), numbers (`FieldNumber`), or dropdowns (`FieldDropdown`) to meet specific needs."],["When subclassing, ensure your constructor matches the super-constructor's signature and register the field with `Blockly.fieldRegistry.register`."],["Implement the `fromJson` method in your custom field class to enable compatibility with the Blockly JSON format for serialization and deserialization."]]],["To extend an existing field, subclass a built-in field like `FieldTextInput` or `FieldColour`, modifying its editor, on-block display, or text. For unique fields, subclass `Field`. Common extensions include `FieldTextInput`, `FieldNumber`, and `FieldDropdown`. Subclass constructors should mirror the super-constructor's signature. Register the field using `Blockly.fieldRegistry.register()` and implement `fromJson` for JSON compatibility. Extending different fields such as `FieldLabelSerializable` is also possible.\n"]]