[英]How to get select element's value in react-bootstrap?
So I'm trying to get a select
element's value in reactjs, but just can't figure it out.所以我试图在 reactjs 中获取
select
元素的值,但无法弄清楚。 The this.refs.selectElement.getDOMNode().value
is always coming as undefined
. this.refs.selectElement.getDOMNode().value
总是以undefined
的形式出现。 All other controls on the form like text
are working fine.表单上的所有其他控件(如
text
)都工作正常。 Any ideas?有任何想法吗? Is it that you can't get the value of
select
element via refs
and must use onChange
event?是不是不能通过
refs
获取select
元素的值,必须使用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: Solution So, if anyone runs into something similar, apparently if you are using react-bootstrap you can't get to the Input
element if you have wrapped it in a ListGroup
.更新:解决方案因此,如果有人遇到类似的情况,显然如果您使用的是 react-bootstrap,则如果将
Input
元素包装在ListGroup
中,则无法访问该元素。 Either take it out from it or wrap all Input
elements in a <form>
tag.要么将其从中取出,要么将所有
Input
元素包装在<form>
标记中。 This solved my issue, thanks for all the help.这解决了我的问题,感谢所有帮助。
it's quite simple:这很简单:
on the render method you should keep an eye on the bind(this)
在 render 方法上,你应该留意
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)
}
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.在这种情况下,您需要使用
getInputDOMNode()
包装函数来获取底层输入的实际 DOM 元素。 But you can also use the getValue()
convenience function that react-bootstrap provides for Input elements .但是您也可以使用react-bootstrap 为 Input elements 提供的
getValue()
便利函数。
So your _handleDube
function 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/
Make a function handleChange().制作一个函数handleChange()。 Then, put it in your render() like this:
然后,像这样把它放在你的 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;
},
"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);
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.
我实际上不得不通过 DOM 层次结构来想出一种提取值的方法。 PS: I did not use
ReactBootstrap.ListGroup
in my code. PS:我没有使用
ReactBootstrap.ListGroup
在我的代码。 Just the Input
from React Bootstrap.只是来自 React Bootstrap 的
Input
。 Here is my code (ES6+).这是我的代码(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",
Refs as strings are considered legacy and may be deprecated .作为字符串的 Refs 被认为是遗留的,可能会被弃用。 But it seems as if react-bootstrap components won't work with callback refs.
但似乎 react-bootstrap 组件不适用于回调引用。 I was working on this today to handle a search input.
我今天正在研究这个以处理搜索输入。
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.我最终抓住了 change 事件并从中获取了价值。 This doesn't feel the "React way" or very current, but it works.
这感觉不像“反应方式”或非常流行,但它有效。
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" />
// ...
}
}
If you are here like me using the latest FormControl
component 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>
}
}
There is yet another easy way!还有一个简单的方法! if you use
<FormGroup>
component and set the controlId
props, the inner DOM ( <input>
, ...) will get that controlId
as its id
attribute.如果您使用
<FormGroup>
组件并设置controlId
道具,则内部 DOM ( <input>
, ...) 将获得该controlId
作为其id
属性。 for example:例如:
<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;
const changeLanguage = (event: any)=> {
console.log('Selected Index : ', event.target.selectedIndex);
}
<Form.Control as="select" onChange={(event)=>{changeLanguage(event)}}>
<option>English</option>
<option>Marathi</option>
</Form.Control>
Note: This solution works with function components.注意:此解决方案适用于功能组件。 For class components we need to change the syntax accordingly.
对于类组件,我们需要相应地更改语法。
: :
Teniendo en cuenta que en la actualidad existe uso obsoleto de getDOMNode() y uso obsoleto de findDOMNode()在 getDOMNode() 和 findDOMNode() 中使用已过时的实际存在
import * as React from 'react'
import Form from 'react-bootstrap/Form'
. . &
&
const Componente1 = (props) => {
let clave = document.getElementById('formSignupPassword').value
console.log(clave)
return (
<>
<Form>
<Form.Group className="mb-2" controlId="formSignupPassword">
<Form.Label className="mb-0">Contraseña</Form.Label>
<Form.Control
type="password"
placeholder="Registre una clave"
/>
</Form.Group>
</Form>
</>
)
}
. . &.
&.
const Componente2 = (props) => {
let passwordText = React.createRef()
let clave = passwordText.current.value
console.log(clave)
return (
<>
<Form>
<Form.Group className="mb-2" controlId="formSignupPassword">
<Form.Label className="mb-0">Contraseña</Form.Label>
<Form.Control
type="password"
placeholder="Registre una clave"
inputRef={passwordText}
// or Use
ref={passwordText}
/>
</Form.Group>
</Form>
</>
)
}
. . ={() =>} &.
={() =>} &。
const Componente3 = (props) => {
const [userEmail, setEmail] = React.useState(null)
console.log(userEmail)
return (
<>
<Form>
<Form.Group className="mb-2" controlId="formSignupEmail">
<Form.Label className="mb-0">Email</Form.Label>
<Form.Control
type="email"
placeholder="Registre una cuenta de email valida"
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
</Form>
</>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.