首页 > 解决方案 > How to properly use callback refs to get selected values in Typescript?

问题描述

I am trying to use the up-to-date method to get a value from a Select element via React but I seem to be getting all kinds of errors. I originally used string refs, but it seems like that is now considered legacy.

class Base extends React.Component<any, any> {
    constructor(props){
    super(props);
    this.candInput = React.createRef();
    this.state = {name: '', ns:'', svc: '', base:'', cand:[]};
}
handleAddCand = (e) => {
        if(!this.state.cand.includes(this.candInput.current.value) &&
            this.state.base !== (this.candInput.current.value)){

            this.setState((prevState) => ({
            cand: [...prevState.cand, this.candInput.current.value],
            }));
        }
}

And the returned components that use the ref is placed like:

<Select
    id="ns-select"
    labelText="Namespace"
    helperText="..."
    ref={this.candInput}
/>
<Button
    onClick={this.handleAddCand}
>
    Add
</Button>

For some reason I keep getting errors that claim that candInput doesn't exist? The compiler err msg is:

Property 'candInput' does not exist on type 'Base'.

And the error that ref is not a property available for this particular element. The element is a imported Carbon Component, but I can't tell if that's the core issue. The error message is:

Property 'ref' does not exist on type 'IntrinsicAttributes & SelectProps & { children?: ReactNode; }'.

My react version is 16.12 and the carbon component version is 7.10, so I definitely have updated modules. Any pointers or help would be greatly appreciated!

标签: node.jsreactjstypescript

解决方案


推荐阅读