react学习
1.构造函数中需要手动改变this – 基于jsx中的函数无法获取this
方法 一:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
// 或者通过 this.handleClick = :: this.handleClick (通过babel编译)
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
方法二:箭头函数 也就是class fild
方法三: jsx箭头函数回调
https://zh-hans.reactjs.org/docs/handling-events.html
2.组件通信之 prop和state
简单概括:
prop
React 组件不能修改传入的 prop
是用于组件直接传值的,但是,修改的时候,需要父组件写一个修改的回调,同时传递给子组件
接收传入的prop:
class Counter extends Component {
constructor(props) {
super (props) ;
this.onClickincrementButton = this.onClickincrementButton.bind(this);
this.onClickDecrementButton = this.onClickDecrementButton.bind(this);
}
}
如果一个组件需要定义自己的构造函数,一定要记得在构造函数的第一行通过 super
state 给组件自身用的,记录自身状态的一个值
constructor (props) {
// 省略号
this.state = {
count: props. initValue || 0
}
}
- propTypes 检测
从语义上就是检测prop值的类型,可以有很多设置,如传值类型,传值方式,是否必填
同时可以通过 defaultProps 设置默认值
Counter.defaultProps = {
initValue: 0
}
4.jsx 语法糖
其实有过vue基础的对语法糖应该不是很陌生,感觉react的语法糖和vue的render有点类似,简单概括,语法糖就是js中可以写html代码