Расширить существующее поле
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Чтобы расширить существующее поле, вы должны создать подкласс встроенного поля (например, FieldTextInput
, FieldColour
), а затем изменить его часть в соответствии с вашими потребностями. Некоторые части поля, которые вы можете изменить:
Если вы хотите создать настраиваемое поле , которому не требуется поведение какого-либо встроенного поля, вам следует создать подкласс Field
.
Общие расширения
Большинство настраиваемых полей расширяют один из этих трех типов:
- Ввод текста : если вы хотите, чтобы пользователи вводили данные в ваше поле, вам следует расширить
FieldTextInput
. - Number : Если вы хотите сохранить число, вам следует расширить
FieldNumber
. - Dropdown : если вы хотите создать раскрывающийся список, но хотите, чтобы в нем хранилась модель, отличная от модели строки или изображения по умолчанию, вам следует расширить
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 MyCustomTextField(value);
}
Дополнительные сведения о регистрации поля см. в разделе «JSON и регистрация» статьи «Создание настраиваемого поля».
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-20 UTC.
[null,null,["Последнее обновление: 2025-08-20 UTC."],[[["\u003cp\u003eTo extend an existing Blockly field, subclass a built-in field like \u003ccode\u003eFieldTextInput\u003c/code\u003e or \u003ccode\u003eFieldColour\u003c/code\u003e and modify its editor, on-block display, or displayed text.\u003c/p\u003e\n"],["\u003cp\u003eFor custom fields with unique behaviors, subclass the base \u003ccode\u003eField\u003c/code\u003e class instead of extending an existing field.\u003c/p\u003e\n"],["\u003cp\u003eCommon field extensions involve customizing text input (\u003ccode\u003eFieldTextInput\u003c/code\u003e), numbers (\u003ccode\u003eFieldNumber\u003c/code\u003e), or dropdowns (\u003ccode\u003eFieldDropdown\u003c/code\u003e) to meet specific needs.\u003c/p\u003e\n"],["\u003cp\u003eWhen subclassing, ensure your constructor matches the super-constructor's signature and register the field with \u003ccode\u003eBlockly.fieldRegistry.register\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eImplement the \u003ccode\u003efromJson\u003c/code\u003e method in your custom field class to enable compatibility with the Blockly JSON format for serialization and deserialization.\u003c/p\u003e\n"]]],["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"],null,["# Extend an existing field\n\nIn order to extend an existing field you must subclass a built in field (e.g\n`FieldTextInput`, `FieldColour`) and then modify part of it to fit your needs.\nSome parts of a field you can modify are:\n\n- Its [editor](/blockly/guides/create-custom-blocks/fields/anatomy-of-a-field#editor_display).\n- Its [on-block display](/blockly/guides/create-custom-blocks/fields/anatomy-of-a-field#on-block_display).\n- The [text](/blockly/guides/create-custom-blocks/fields/anatomy-of-a-field#text) it displays.\n\nIf you want to [create a\ncustom field](/blockly/guides/create-custom-blocks/fields/customizing-fields/creating)\nthat does not need behaviour from any built-in field you should subclass `Field`.\n\nCommon extensions\n-----------------\n\nMost custom fields extend one of these three types:\n\n- [Text Input](/blockly/guides/create-custom-blocks/fields/built-in-fields/text-input): If you want your users to type into your field, you should extend `FieldTextInput`.\n- [Number](/blockly/guides/create-custom-blocks/fields/built-in-fields/number): If you want to store a number, you should extend `FieldNumber`.\n- [Dropdown](/blockly/guides/create-custom-blocks/fields/built-in-fields/dropdown): If you want to create a dropdown, but you want it to store a different model than the default string or image model, you should extend `FieldDropdown`.\n - Caution: Before extending `FieldDropdown`, check that the dropdown field's [customization options](/blockly/guides/create-custom-blocks/fields/built-in-fields/dropdown#customization) cannot fulfill your needs.\n\nUnder certain circumstances you may wish to extend a different field type. For\nexample `FieldLabelSerializable` extends `FieldLabel`.\n\nSubclassing\n-----------\n\n import * as Blockly from 'blockly';\n\n export class MyCustomTextField extends Blockly.FieldTextInput {\n\n constructor(value, validator, config) {\n super(value, validator, config);\n }\n }\n\nThe constructor for a field's subclass looks very similar to the [constructor for\na custom field](/blockly/guides/create-custom-blocks/fields/customizing-fields/creating#implementing_a_constructor). The signature of the sub-constructor should\ngenerally match the signature of the super-constructor.\n\nJSON and registration\n---------------------\n\nYou should also register the field once: \n\n Blockly.fieldRegistry.register('my_custom_text_field', MyCustomTextField);\n\nand provide an implementation of `fromJson` in the class so that it works with\nthe JSON format: \n\n static fromJson(options) {\n const value = Blockly.utils.parsing.replaceMessageReferences(options.value);\n return new MyCustomTextField(value);\n }\n\nFor more information about registering a field see the [JSON and registration](/blockly/guides/create-custom-blocks/fields/customizing-fields/creating#json_and_registration)\nsection in Creating a Custom Field."]]