render是类式中必要的
构造器的作用:
注意:
为什么写构造器,必调super()?
打印实例自身props
如果构造器不写props
就获取不到实例的props
如果接了props但又没传给props,会导致接了没啥用,主要是要给super传过去:
总结:
类中构造器可以省略(开发时候能省略就省略)
如果希望获得实例的props就要写构造器,如果写构造器,就要传props,不然获取不到this.props
案例,传递回调函数作为 Props
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
inputValue: event.target.value
});
}
render() {
return (
<div>
{ /* change code below this line */ }
<GetInput input={this.state.inputValue}
handleChange={this.handleChange} />
<RenderInput input={this.state.inputValue} />
{ /* change code above this line */ }
</div>
);
}
};
class GetInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Get Input:</h3>
<input
value={this.props.input}
onChange={this.props.handleChange}/>
</div>
);
}
};
class RenderInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h3>Input Render:</h3>
<p>{this.props.input}</p>
</div>
);
}
};
在输入框输入,在下方会显示