无法读取null的属性'值'?
问题描述:
我在尝试使用this.username.value
时出现错误。我想获得文本框的价值以显示在标签中。我是新手反应。如何从文本框中获取值到变量并使用InputRef在标签中显示。无法读取null的属性'值'?
答
在你的问题中有一些错误。试着去了解下一个代码和你将能够将它应用到你的例子:
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
value: "",
username: ""
}
}
handleChange(e){
this.setState({value: e.target.value})
}
handleClick(){
this.setState({username: this.state.value})
}
render(){
return (
<div>
<label>{this.state.username}</label><br />
<input value={this.state.value} onChange={this.handleChange.bind(this)}></input><br />
<button onClick={this.handleClick.bind(this)}>Login</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'/>