我有一个React Native片段,它是export default connect(mapStateToProps, mapDispatchToProps)($0)
,光标出现在最后的parens中,所以我可以输入类名。
假设我总是在一个已定义类的文件(class ClassName extends Component {
)中使用此片段,是否有办法编写片段以便它自动填充当前的ClassName?使用正则表达式或其他东西,开始。
例如,在文件开头给出此代码:
import React, { Component } from "react";
import { connect } from "react-redux";
class MyClass extends Component {
...
...
当我在该文件中键入我当前export default connect(mapStateToProps, mapDispatchToProps)($0)
的代码段快捷方式(它给我带有$0
所在光标的代码)我想让它立即得到这个:
export default connect(mapStateToProps, mapDispatchToProps)(MyClass)
也许它是这样的:
"body": "export default connect(mapStateToProps, mapDispatchToProps)({/class (\w+) extends/})"```
除了转换其中一个内置变量之外,您不能将正则表达式放入代码段中。如果MyClass
已经在剪贴板上,你可以在你的代码片段中使用$CLIPBOARD
:
"body": "export default connect(mapStateToProps, mapDispatchToProps)($CLIPBOARD)"
假设你不总是总是在剪贴板上有类名,有另一个棘手的方法来找到类名,选择它并将其复制到剪贴板,以便它可以作为$CLIPBOARD
在一个片段中使用。
首先,您需要像multi-command这样的宏扩展。
其次,settings.json中的这个设置:
"multiCommand.commands": [
{
"command": "multiCommand.regexSnippet", // name of the macro to use a keybinding
"interval": 1000, // delay between the following commands, left long to watch it work
// you don't need any interval, that option can be commented out
"sequence": [
// first command, on a blank line type out a regular expression
{
"command": "type",
"args": {
"text": "(?<=class )(.*)(?= extends)"
}
},
// select and cut that regex
"cursorHomeSelect",
"editor.action.clipboardCutAction",
// now $CLIPBOARD has your class name on it
// open the find widget
"actions.find",
// "toggleFindRegex", // you should have the find regex option already selected
// paste the regex into the find widget
"editor.action.clipboardPasteAction",
// select and copy the match that the regex finds
"editor.action.selectAllMatches",
"editor.action.clipboardCopyAction",
// go back to where you were in the code to insert the snippet
"workbench.action.navigateToLastEditLocation",
{
"command": "editor.action.insertSnippet",
"args": {
// "snippet": "export default $1($2, $3)($CLIPBOARD)",
// use the above if those values are not pre-determined like in your question
"snippet": "export default connect(mapStateToProps, mapDispatchToProps)($CLIPBOARD)"
}
}
]
}
],
第三,一些键绑定触发这个宏:
{
"key": "shift-alt-2",
"command": "multiCommand.regexSnippet"
},
注意:您正在触发宏,而不是片段 - 因此没有智能感知。
这是一个具有长间隔的gif,因此您可以看到操作步骤(“切换截屏模式”以查看命令键):
几个要点:
class MyClass extends
这个宏可能不起作用。如果这对您有用,请告诉我。