使用react-bootstrap获取输入文本的值

问题描述 投票:1回答:2

我尝试将值添加到输入文本中,并使用react-bootstrap将其添加到文本区域。

我知道我必须使用ReactDOM.findDOMNode来获取ref的值。我不明白出了什么问题。

这是我的代码:

import React from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import { InputGroup, FormGroup, FormControl, Button} from 'react-bootstrap';
import './App.css';
class InputMessages extends React.Component {
constructor(props) { 
super(props);
this.handleChange =      this.handleChange.bind(this); 
    this.GetMessage= this.GetMessage.bind(this); 
this.state = {message: ''};
}   
handleChange(event)
{    
this.setState({message: this.GetMessage.value});
}
GetMessage()
{   
return ReactDOM.findDOMNode(this.refs.message     );
 }
 render() {
    var message = this.state.message;
    return(
 <FormGroup > 
 <FormControl
 componentClass="textarea" value={message} />
 <InputGroup> 
 <FormControl type="text" ref='message' /> 
    <InputGroup.Button>
    <Button bsStyle="primary" onClick={this.handleChange}>Send
    </Button>
    </InputGroup.Button> 
    </InputGroup>
    </FormGroup>
    );
   }
   }  
   export default InputMessages;
javascript reactjs textarea react-bootstrap textinput
2个回答
1
投票

在表单中添加一个输入引用:

<FormControl inputRef={ref => { this.myInput = ref; }} />

所以现在你得到的价值就像

this.myInput.value

3
投票

Form Control有一个ref prop,它允许我们使用React Refs

示例代码:

class MyComponent extends React.Component {
  constructor() {
     /* 1. Initialize Ref */
     this.textInput = React.createRef(); 
  }

  handleChange() {
     /* 3. Get Ref Value here (or anywhere in the code!) */
     const value = this.textInput.current.value;
  }

  render() {
    /* 2. Attach Ref to FormControl component */
    return (
      <div>
        <FormControl ref={this.textInput} type="text" onChange={() => this.handleChange()} />
      </div>
    )
  }
}

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.