【问题标题】:Get value of input text with react-bootstrap使用 react-bootstrap 获取输入文本的值
【发布时间】:2017-12-24 22:59:08
【问题描述】:

我尝试在输入文本中获取值并使用 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;

【问题讨论】:

  • 在寻求帮助时,花时间合理地格式化您的代码并保持一致性可能会帮助您获得更好/更快的答案。此外,请考虑使用 Stack Snippets([&lt;&gt;] 工具栏按钮)通过 runnable minimal reproducible example 更新您的问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.

标签: javascript reactjs textarea react-bootstrap textinput


【解决方案1】:

表单控件有一个refprop,它允许我们使用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>
    )
  }
}

希望这会有所帮助!

【讨论】:

  • 非常有帮助!谢谢!!
【解决方案2】:

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

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

所以现在你得到了像

this.myInput.value

【讨论】:

  • 它有效,但我将值存储在状态中。我想将它存储到变量中。我使用了 2 个组件,所以我无法将 this.myinput.value 写入其他组件
  • componentClass="textarea" value={this.input.value} /> 不识别 ref,而函数识别
猜你喜欢
  • 1970-01-01
  • 2018-01-14
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
相关资源
最近更新 更多