Javascript 如何在 React 中获取文本框的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38420396/
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 value of textbox in React?
提问by Lucas
I just started using React.js, and I'm just not sure whether there is a special way to get the value of a textbox, returned in a component like this:
我刚开始使用 React.js,我只是不确定是否有一种特殊的方法来获取文本框的值,在这样的组件中返回:
var LoginUsername = React.createClass({
render: function () {
return (
<input type="text" autofocus="autofocus" onChange={this.handleChange} />
)
},
handleChange: function (evt) {
this.setState({ value: evt.target.value.substr(0, 100) });
}
});
回答by Dmitriy Nevzorov
As described in documentationYou need to use controlled input. To make an input - controlledyou need to specify two props on it
如文档中所述,您需要使用受控输入。要进行输入控制,您需要在其上指定两个道具
onChange
- function that would set componentstate
to an inputvalue
every time input is changedvalue
- input value from the componentstate
(this.state.value
in example)
onChange
-每次输入更改时将组件设置state
为value
输入的功能value
- 来自组件的输入值state
(this.state.value
在示例中)
Example:
例子:
getInitialState: function() {
return {value: 'Hello!'};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
);
}
More specifically about textarea - here
更具体地说是关于 textarea -这里
回答by Piyush.kapoor
just update your input to the value
只需将您的输入更新为该值
var LoginUsername = React.createClass({
getInitialState:function(){
return {
textVal:''
}
},
render: function () {
return (
<input type="text" value={this.state.textVal} autofocus="autofocus" onChange={this.handleChange} />
)
},
handleChange: function (evt) {
this.setState({ textVal: evt.target.value.substr(0, 100) });
}
});
Your text input value is always in the state and you can get the same by this.state.textVal
您的文本输入值始终处于状态中,您可以通过 this.state.textVal 获得相同的值