2 way Function binding - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
2-way function binding
Two way to bind a function to a component as following:
- Binding in constructor
export class Test extends Component {
constructor(props){
super(props);
this.submit = this.submit.bind(this);
}
submit(e){
e.preventDefault();
console.log('resort', this.refs.resort.value);
console.log('date', this.refs.date.value);
console.log('powder', this.refs.powder.checked);
console.log('backcountry', this.refs.backcountry.checked);
}
render(){
return (
<form onSubmit={this.submit} className="add-day-form">
Using bind()
method to bind itself.
- Binding using property initializer syntax
In ES6 class:
export class Test extends Component {
submit = (e) => {
e.preventDefault();
console.log('resort', this.refs.resort.value);
console.log('date', this.refs.date.value);
console.log('powder', this.refs.powder.checked);
console.log('backcountry', this.refs.backcountry.checked);
}
render(){
return (
<form onSubmit={this.submit} className="add-day-form">
In stateless function:
export const Test = ({ resort,
date,
powder,
backcountry
}) => {
let _resort, _date, _powder, _backcountry;
const submit = (e) => {
e.preventDefault();
_resort.value='';
_date.value='';
_powder.checked=false;
_backcountry.checked=false;
}
return (
<form onSubmit={submit} className="add-day-form">
Binding make 'this' work in callback function