1.React.createRef()
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
return (
<div>
<input
type="text"
ref={this.textInput} />
</div>
);
}
}
- React.createRef可以給Dom元素添加ref。
- React.createRef可以給Class組件添加ref。
- React.createRef不能給函數(shù)式組件使用!瘪贱!
回調(diào)Refs
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
}
render() {
return (
<input
type="text"
ref={this.setTextInputRef}
/>
);
}
}