Solid.js中指令作为Props传递给自定义组件失效问题排查及解决方案咨询
Great question! This isn’t an error on your part—it’s an intentional design choice in Solid.js around how custom directives operate. Let’s break down what’s happening and how to fix it.
What’s the Root Cause?
Solid.js custom directives are only built to work directly with native DOM elements, not with custom components. When you add use:inputLogger to your CustomInput component, the framework can’t automatically pass that directive down to the <input> inside the component. Components are logical wrappers, not actual DOM nodes, so the directive has no DOM element to attach to.
Practical Fixes
Here are a few straightforward solutions depending on your needs:
1. Apply the Directive Directly Inside the Component
If every instance of CustomInput should use the inputLogger directive, just add it directly to the native <input> in your component:
const CustomInput: Component<JSX.InputHTMLAttributes<HTMLInputElement>> = (props) => { return <input {...props} use:inputLogger /> }
Now whenever you use <CustomInput />, the directive will be active by default.
2. Forward Directives to the Native Input (Flexible Approach)
If you need CustomInput to accept arbitrary directives from its parent, use forwardRef to turn your component into a transparent wrapper for the native input. This lets Solid pass through directives directly to the underlying DOM element:
import { Component, forwardRef } from "solid-js"; const CustomInput = forwardRef<HTMLInputElement, JSX.InputHTMLAttributes<HTMLInputElement>>( (props, ref) => { return <input ref={ref} {...props} />; } );
Now when you use <CustomInput use:inputLogger />, the directive will attach to the inner native input just like it does on a regular <input>.
3. Use a "Native Alias" Component
For simple wrappers that don’t add complex logic beyond props, you can treat your component as an alias for the native input. This makes it inherit all native behavior, including directive support:
const CustomInput = "input" as Component<JSX.InputHTMLAttributes<HTMLInputElement>>;
This is the simplest option if your component is just a thin wrapper around the native input.
Is This a Framework Limit?
Not exactly—it’s a deliberate design choice. Solid.js prioritizes direct DOM access and performance, so directives are tightly coupled to actual DOM nodes rather than abstract components. This keeps the framework fast but means you need to explicitly handle directive forwarding if you want them to work with custom components.
内容的提问来源于stack exchange,提问作者Owl

