Component as a property with omitted parameters
P粉803527801
P粉803527801 2024-04-03 20:25:34
0
1
383

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粉803527801
P粉803527801

reply all(1)
P粉425119739

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}/>

in the input

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 } />

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template