Get value of input text with react-bootstrap

自作多情 提交于 2020-07-20 17:00:27

问题


I try to get value into a input text and add it to a text area with react-bootstrap.

I know I must use ReactDOM.findDOMNode to get value with ref. I don't understand what is wrong.

Here my code :

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;

回答1:


Add an Input ref to your form :

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

so now you get the value like

this.myInput.value



回答2:


Form Control has a ref prop, which allows us to use React Refs

Sample Code :

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>
    )
  }
}

Hope this helps!



来源:https://stackoverflow.com/questions/45194498/get-value-of-input-text-with-react-bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!