之前写ref绑定的时候,一直报错Cannot read property 'refs' of undefined 打印发现this指向为undefined,最后发现用bind绑定就可以啦
<body>
<div id="root"></div>
<script type="text/babel">
class HelloComment extends React.Component{
handleClick(){
this.refs.myInput.focus();
}
render(){
return (
<div>
<input type="text" ref="myInput"/>
<input type="button"
value="Focus the text input"
onClick={this.handleClick.bind(this)}/>
</div>
)
}
}
ReactDOM.render(
<HelloComment/>,
document.getElementById("root")
)
</script>
</body>
还有一种写法:
<body>
<div id="root"></div>
<script type="text/babel">
class HelloComment extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.textInput.focus();
}
render(){
return (
<div>
<input type="text" ref={(input) => { this.textInput = input; }} />
<input type="button"
value="Focus the text input"
onClick={this.handleClick}/>
</div>
)
}
}
ReactDOM.render(
<HelloComment/>,
document.getElementById("root")
)
</script>
</body>
纪念保存此篇~~~