class Greeter extends React.Component {
constructor(props) {
super(props);
this.handleNewName = this.handleNewName.bind(this);
this.state = {
name: this.props.name
};
}
static defaultProps = {
name: 'user',
message: 'This is a default message'
}
handleNewName(name) {
this.setState({
name: name
});
}
render() {
let name = this.state.name,
message = this.props.message;
return (
<div>
<GreeterMessage />
<GreeterForm onNewName={this.handleNewName} />
</div>
);
}
}
class GreeterMessage extends Greeter {
constructor(props) {
super(props);
}
render() {
let name = this.props.name;
return(
<div>
<h1>Hello {name}!</h1>
<p>Some text</p>
</div>
);
}
}
class GreeterForm extends Greeter {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
e.preventDefault();
let name = this.refs.name.value;
if(name.length > 0) {
this.refs.name.value = '';
this.props.onNewName(name);
}
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<input type="test" ref="name" />
<button>Set Name</button>
</form>
);
}
}
let name = 'User';
ReactDOM.render(
<Greeter name={name} />,
document.getElementById('app')
)
class Foo {
onSubmit = (event) => {
// "this" is correct instance
};
}