Javascript 如何在react-bootstrap中获取select元素的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28678466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get select element's value in react-bootstrap?
提问by Raza Gill
So I'm trying to get a selectelement's value in reactjs, but just can't figure it out. The this.refs.selectElement.getDOMNode().valueis always coming as undefined. All other controls on the form like textare working fine. Any ideas? Is it that you can't get the value of selectelement via refsand must use onChangeevent?
所以我试图select在 reactjs 中获取一个元素的值,但就是想不通。将this.refs.selectElement.getDOMNode().value始终为即将到来undefined。表单上的所有其他控件text都可以正常工作。有任何想法吗?是不是不能通过select元素获取值refs而必须使用onChange事件?
Updated:
更新:
var TestSelectClass = React.createClass({
mixins: [Router.Navigation],
_handleDube: function(event) {
DubeActionCreators.DubeTest({
message: this.refs.message.getDOMNode().value,
tax: this.refs.tax.getDOMNode().value,
validity: this.refs.valid_for.getDOMNode().value
});
},
render: function() {
return (
<ReactBootstrap.ListGroup>
<textarea
className="form-control"
rows="3"
placeholder="Enter message"
ref="message" >
</textarea>
<div className="input-group">
<span className="input-group-addon" id="basic-addon1">$</span>
<input type="text" className="form-control" placeholder="10" aria-describedby="basic-addon1" ref="tax" />
</div>
<Input type="select" value="1" ref="valid_for">
<option value="1">1 hour</option>
<option value="2">1 day</option>
<option value="2">5 days</option>
</Input>
</ReactBootstrap.ListGroup>
)
}
});
Updated: SolutionSo, if anyone runs into something similar, apparently if you are using react-bootstrap you can't get to the Inputelement if you have wrapped it in a ListGroup. Either take it out from it or wrap all Inputelements in a <form>tag. This solved my issue, thanks for all the help.
更新:解决方案因此,如果有人遇到类似的情况,显然如果您使用的是 react-bootstrap,Input如果您将其包装在ListGroup. 要么从中取出它,要么将所有Input元素包装在一个<form>标签中。这解决了我的问题,感谢所有帮助。
采纳答案by julen
I see you are using react-bootstrap, which includes a wrapper around regular input elements.
我看到您正在使用react-bootstrap,其中包含一个围绕常规输入元素的包装器。
In this case you need to use the getInputDOMNode()wrapper function in order to get the underlying input's actual DOM element. But you can also use the getValue()convenience function that react-bootstrap provides for Input elements.
在这种情况下,您需要使用getInputDOMNode()包装器函数来获取底层输入的实际 DOM 元素。但是您也可以使用react-bootstrap 为 Input elements 提供的getValue()便利功能。
So your _handleDubefunction should look like:
所以你的_handleDube函数应该是这样的:
_handleDube: function(event) {
DubeActionCreators.DubeTest({
message: this.refs.message.getInputDOMNode().value,
tax: this.refs.tax.getInputDOMNode().value,
validity: this.refs.valid_for.getValue()
});
},
See this JSFiddle for a complete example: http://jsfiddle.net/mnhm5j3g/1/
有关完整示例,请参阅此 JSFiddle:http: //jsfiddle.net/mnhm5j3g/1/
回答by Alejandro Silva
it's quite simple:
这很简单:
on the render method you should keep an eye on the bind(this)
在渲染方法上,你应该留意 bind(this)
<select onChange={this.yourChangeHandler.bind(this)}>
<option value="-1" disabled>--</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
and your handler is like:
你的处理程序就像:
yourChangeHandler(event){
alert(event.target.value)
}
回答by ritmatter
Make a function handleChange(). Then, put it in your render() like this:
制作一个函数handleChange()。然后,像这样把它放在你的 render() 中:
<Input type="select" value="1" ref="valid_for" onChange={this.handleChange}>
And the function in the component:
以及组件中的函数:
handleChange: function(e) {
var val = e.target.value;
},
回答by Fizzy Chan
"react": "^15.0.2",
"react-bootstrap": "^0.29.3",
"react-dom": "^15.0.2",
under the env, ReactDOM.findDOMNode() works for me.
在环境下, ReactDOM.findDOMNode() 对我有用。
in render():
在渲染()中:
<FormControl name="username" ref="username"/>
in handler():
在处理程序()中:
const username = findDOMNode(this.refs.username);
回答by AndyFaizan
None of the above worked for me. I actually had to go through the DOM hierarchy to come up with a way to extract the value.
PS: I did notuse ReactBootstrap.ListGroupin my code. Just the Inputfrom React Bootstrap. Here is my code (ES6+).
以上都不适合我。我实际上不得不通过 DOM 层次结构来想出一种提取值的方法。PS:我并没有用ReactBootstrap.ListGroup在我的代码。只是Input来自 React Bootstrap。这是我的代码(ES6+)。
import ReactDOM from 'react-dom';
getValueFromSelect(ref){
var divDOMNode = ReactDOM.findDOMNode(ref);
/* the children in my case were a label and the select itself.
lastChild would point to the select child node*/
var selectNode = divDOMNode.lastChild;
return selectNode.options[selectNode.selectedIndex].text;
}
Dependencies:
依赖项:
"react": "^0.14.3",
"react-bootstrap": "0.28.1",
"react-dom": "^0.14.3",
回答by mccambridge
Refs as strings are considered legacy and may be deprecated. But it seems as if react-bootstrap components won't work with callback refs. I was working on this today to handle a search input.
作为字符串的 Refs 被认为是遗留的,可能会被弃用。但似乎 react-bootstrap 组件不适用于回调引用。我今天正在研究这个以处理搜索输入。
class SearchBox extends Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.props.updateQuery(this._query.value);
}
render() {
// ...
<FormControl
onChange={this.handleChange}
ref={(c) => this._query = c} // should work but doesn't
value={this.props.query}
type="text"
placeholder="Search" />
// ...
}
}
I wound up grabbing the change event and getting the value from it. This doesn't feel the "React way" or very current, but it works.
我最终抓住了 change 事件并从中获取了价值。这感觉不像“反应方式”或非常流行,但它有效。
class SearchBox extends Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.updateQuery(e.target.value);
}
render() {
// ...
<FormControl
onChange={this.handleChange}
value={this.props.query}
type="text"
placeholder="Search" />
// ...
}
}
回答by Majid
There is yet another easy way! if you use <FormGroup>component and set the controlIdprops, the inner DOM (<input>, ...) will get that controlIdas its idattribute. for example:
还有一个简单的方法!如果您使用<FormGroup>组件并设置controlId道具,则内部 DOM ( <input>, ...) 将获得它controlId作为其id属性。例如:
<FormGroup controlId="myInputID">
<ControlLabel>Text</ControlLabel>
<FormControl type="text" placeholder="Enter text" />
</FormGroup>
Then you will have the value by calling document.getElementById:
然后您将通过调用获得价值document.getElementById:
var myInputValue = document.getElementById("myInputID").value;
回答by JohnnyQ
If you are here like me using the latest FormControlcomponent here's a solution I did:
如果你像我一样在这里使用最新的FormControl组件,这是我做的一个解决方案:
import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Blah extends Component {
getSelectValue = () => {
/* Here's the key solution */
console.log(ReactDOM.findDOMNode(this.select).value)
}
render() {
return
<div>
<FormControl
ref={select => { this.select = select }}
componentClass="select"
disabled={this.state.added}
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</FormControl>
<Button onclick={this.getSelectValue}>
Get Select value
</Button>
</div>
}
}

