Refs được tạo bằng phương thức React.createRef() và được gắn vào các React element qua thuộc tính ref. Để sử dụng các ref trong toàn bộ component, chỉ cần gán ref này tới 1 property trong constructor.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
và:
class UserForm extends Component {
handleSubmit = () => {
console.log('Input Value is: ', this.input.value);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={(input) => (this.input = input)} /> // Access DOM input in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
Chúng ta cũng có thể sử dụng nó trong các functional component với sự trợ giúp của closure.