【问题标题】:What typescript type should I use for Reactstrap Input Ref?我应该为 Reactstrap Input Ref 使用什么打字稿类型?
【发布时间】:2021-07-06 19:08:13
【问题描述】:

我将 ref 链接到 <Input> 元素,但无法获得正确的类型来定义它。目前我有这个:

const [location, setLocation] = useState<GeolocationPosition>();
  const [search, setSearch] = useState<string>('');
  
  const searchInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(position => {
      setLocation(position);
    })
  }, [])

  const changeSearchHandler = () => {
    setSearch(searchInputRef.current!.value);
  }

  return (
    <>
      <Row>
        <Col className='header'>
          <h3 className='mt-3'>IsItOpen?</h3>
        </Col>
      </Row>
      <Row className='mt-4'>
        <Col lg={{ size: 6, order: 0, offset: 3}}>
          <Card>
            <CardHeader>
              <CardTitle>
                <Input type='text' ref={searchInputRef} onChange={changeSearchHandler} />
              </CardTitle>
            </CardHeader>
            <CardBody>
              Your results!
            </CardBody>
          </Card>
        </Col>
      </Row>
    </>
  );

错误来自&lt;Input&gt; 告诉我的行:

类型 RefObject 不能分配给类型 LegacyRef

如果我将 ref 类型更改为 Input,那么我会在 setSearch 调用中的 value 上收到错误消息:

输入类型上不存在属性“值”

我不确定正确的方法是什么,我不想使用any

【问题讨论】:

    标签: javascript reactjs typescript reactstrap


    【解决方案1】:

    React-strap 提供了另一个 prop,innerRef 让你访问底层的&lt;input /&gt;

    const searchInputRef = useRef<HTMLInputElement>(null);
    
    const changeSearchHandler = () => {
      setSearch(searchInputRef.current!.value);
    };
    
    // ..
    
    <Input
      type="text"
      innerRef={searchInputRef}
      onChange={changeSearchHandler}
    />
    

    ref 允许您访问 react-strap 的 Input 组件。

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 2019-07-22
      • 2021-04-26
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      相关资源
      最近更新 更多