5

我一直在尝试从一个input字段中获取输入,并且我使用refs了(通常的方式react),但它似乎没有工作。input我得到的是undefined。这是我的代码:

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 event按钮的输入。我不知道出了什么问题。我怎样才能input正确获得价值?

4

3 回答 3

9

在您的情况下,您还可以通过以下代码获取输入值:

this.inputtext.inputRef.value
于 2017-07-28T10:58:28.610 回答
6

由于您使用了arrow运算符,this.inputtext.value因此无法正常工作,您需要编写:

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

在这种情况下,语义用户界面的Input组件是div包装在input. 所以你不能直接通过 ref 访问输入元素。您应该使用反应的首选方式来获取价值,即

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


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

或不使用绑定,babel-preset-stage-2这是必需的。

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


handleMessage = e => { console.log(e.target.value); }
于 2017-03-10T11:20:22.717 回答
1

您需要使用普通的类方法才能使其工作。您也不应该在参考文献中使用分号。

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

  render(){
     return(
       <div>
        <Input ref={input => this.inputtext = input} placeholder='message'/>
        <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
  }
于 2017-03-10T11:32:32.113 回答