ANTD获取Input组件值的两种方法


今天试着用antd的组件取开发网页,用useRef勾子去获取Input组件的值,发现会报错,然后去输出了一下Input组件的属性,antd只是在input上封装了一层而已。

1.使用event.target.value

万金油用法event.target.value

import React from 'react';
import { Input } from 'antd';

function InputWord(){
  const change1 =(event)=>{
    word = event.target.value
    console.log(word)
  }
 //省略
 
return(
      <Input  type="text" onChange={change1} placeholder="Word" ></Input>

)

}

2.使用ref勾子

直接用ref.current.value出错是因为这不是基础的html组件,Input组件是在基础输入框input上的一个封装,要找到Input组件里面的基础input组件,才有value值。

import React {useRef} from 'react';
import { Input } from 'antd';

function InputSentence(){
  const input2 = useRef(null)
  const change2 =(event)=>{
    sentence = input2.current.input.value
    console.log(sentence)
  }
 //省略
 
return(
      <Input ref={input2} type="text" onChange={change2} placeholder="Sentence" ></Input>

)

}

因为Input组件把输入框的值也存放到,我试着用input2.current.state.value去取,但是总是取上一次的结果,这说明了在onChange调用change2 函数的时候,组件还没有开始setState,如果是写非受控组件的话也是可以这么用的,因为已经渲染完成了。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐