I want to define a property that must be a component with an omitted property.
I have a validation component with some properties:
interface ValidationProps { value: string, check: Array<(value) => boolean> } const Validation: FC<ValidationProps> = function(){} export default Validation;
I have an input component.
interface InputProps { value: string, onChange: (e: SyntaticEvent) => void, validations: ??? } const Input: FC<InputProps> = function(props){ return <span> <input value={props.value} onChange={props.onChange} /> {React.cloneElement(props.validations, {value})} </span> } export default Input;
So I want to define InputProps.validations must be a Validation but omit the value prop.
should be used like this:
<Input value="value" onChange={...} validations={<Validation check={[(value) => value != null, (value) => value.length <= 5]} />} />
P粉4251197392024-04-04 09:27:11
I'm not completely clear on what you want to achieve here, so I'm probably missing something...
But you cannot directly specify that prop must be a component with specific properties. You can , but specify validations: omit <ValidationProps, 'value'/>
and substitute {React.cloneElement(props.validations, {value})}
Just instantiate your <validation check={props.validations} value={value}/>
renew:
If you don't want a dependency between two components (input and validation), there can't be a dependency between the props interfaces either, unless you share them in a third module imported by both.
In this case, you can abstract further and make the validations a render prop, like validations: (value) => ReactElement
. It can then be used as before, but with the added "thick arrow" syntax
value != null, (value) => value.length <= 5]} />} />
Just call validations(value)
to instantiate instead of cloneElement
.
This does abstract it to the point of too much flexibility, since anything can be injected into the validation render props.