研究调查问卷:请告诉我们您使用 Blockly 的体验
开始调查问卷
扩展现有字段
要扩展现有字段,您必须将内置字段(例如
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 和注册
部分。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-09-08。
[null,null,["最后更新时间 (UTC):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"]]