加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 如何从反应语义UI中获取输入

发布时间:2020-12-15 09:33:17 所属栏目:百科 来源:网络整理
导读:我一直在尝试从输入字段中获取输入,并且我使用了refs(通常的反应方式),但它似乎没有起作用.我得到的输入是未定义的.这是我的代码: sendMessage = () = { console.log(this.inputtext.value);}render(){ return( div Input ref={input = this.inputtext = in
我一直在尝试从输入字段中获取输入,并且我使用了refs(通常的反应方式),但它似乎没有起作用.我得到的输入是未定义的.这是我的代码:

sendMessage = () => {
   console.log(this.inputtext.value);
}

render(){
   return(
      <div>
         <Input ref={input => this.inputtext = input;} placeholder='message'/>
         <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
}

我需要从按钮的click事件中获取输入.我无法弄清楚出了什么问题.如何正确获取输入值?

解决方法

由于您使用了箭头运算符,this.inputtext.value将不起作用,
你需要写:

sendMessage(){
  console.log(this.inputtext.value);
}

在这种情况下,semantic-ui的Input Component是一个包含在输入之上的div.所以你不能直接通过ref访问input元素.您应该使用react的首选方法来获取值,即

<Input onChange={this.handleMessage.bind(this)} placeholder='message'/>


handleMessage (e) { console.log(e.target.value); }

或者不使用bind,需要babel-preset-stage-2.

<Input onChange={this.handleMessage} placeholder='message'/>


handleMessage = e => { console.log(e.target.value); }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读