Javascript 如何在reactjs版本16.13.1中获取输入文本的值
我是新来的。我正在阅读一份关于如何获取输入值的文档。但我仍然得到一个未定义的错误。这就是我所做的Javascript 如何在reactjs版本16.13.1中获取输入文本的值,javascript,reactjs,Javascript,Reactjs,我是新来的。我正在阅读一份关于如何获取输入值的文档。但我仍然得到一个未定义的错误。这就是我所做的 class Test extends React.Component{ constructor(props){ super(props) this.inputRef = React.createRef() } clickHandler(){ console.log(this.inputRef) } render(){ return( &
class Test extends React.Component{
constructor(props){
super(props)
this.inputRef = React.createRef()
}
clickHandler(){
console.log(this.inputRef)
}
render(){
return(
<div>
<input type="text" ref={this.inputRef}/>
<button onClick={this.clickHandler}>click Me</button>
</div>
)
}
}
ReactDOM.render(<Test />, document.getElementById('root'));
类测试扩展了React.Component{
建造师(道具){
超级(道具)
this.inputRef=React.createRef()
}
clickHandler(){
console.log(this.inputRef)
}
render(){
返回(
点击我
)
}
}
ReactDOM.render(,document.getElementById('root'));
您的问题是没有将clickHandler绑定到组件
最简单的方法是使用箭头函数而不是类方法:
clickHandler=()=>{
console.log(this.inputRef)
}
否则,在构造函数中,您需要手动绑定clickHandler:
constructor(props){
super(props)
this.inputRef = React.createRef()
this.clickHandler = this.clickHandler.bind(this);
}
下面是一个使用arrow函数(自动绑定)的示例
类测试扩展了React.Component{
inputRef=React.createRef()
clickHandler=()=>{
log(this.inputRef.current.value)
}
render(){
返回(
点击我
)
}
}
ReactDOM.render(,document.getElementById('root'))代码>