useExpressionScope
描述
读取当前子树的 Schema 表达式作用域。createSchemaField 与 ExpressionScope 注入的变量都可以通过该 hook 在自定义组件中读取。
签名
ts
declare function useExpressionScope(): any用例
tsx
import { ExpressionScope, useExpressionScope } from '@silver-formily/react'
import { Typography } from 'antd'
// 读取当前子树的表达式作用域,常用于自定义组件消费 scope 中的变量
function Custom() {
const scope = useExpressionScope() as { text?: string } | undefined
return (
<Typography.Text>
作用域中的 text:
{scope?.text ?? '未注入'}
</Typography.Text>
)
}
export default function Demo() {
return (
<div>
<div style={{ marginBottom: 8 }}>
<Custom />
</div>
<ExpressionScope value={{ text: '来自 ExpressionScope 的值' }}>
<Custom />
</ExpressionScope>
</div>
)
}tsx
import { ExpressionScope, useExpressionScope } from '@silver-formily/react'
import { Typography } from 'antd'
// 读取当前子树的表达式作用域,常用于自定义组件消费 scope 中的变量
function Custom() {
const scope = useExpressionScope() as { text?: string } | undefined
return (
<Typography.Text>
作用域中的 text:
{scope?.text ?? '未注入'}
</Typography.Text>
)
}
export default function Demo() {
return (
<div>
<div style={{ marginBottom: 8 }}>
<Custom />
</div>
<ExpressionScope value={{ text: '来自 ExpressionScope 的值' }}>
<Custom />
</ExpressionScope>
</div>
)
}
查看源码
该 hook 只读取上下文,不创建模型,也不订阅模型属性。应在对应 Provider 下使用;即使部分签名未声明空值,缺少或被清理的上下文在运行时仍可能返回 null/undefined。