React起步

1、首先搭建一个单页面应用
npx create-react-app my-app
cd my-app
npm start
2、react组件

react项目一般都是搭配jsx语言使用,jsx只是js的一个语法扩展,可以让你在render里写dom结构的时候能够被识别,而且可以很好地使用表达式有提示。
我们知道,react是一个专注于组件化的框架,他在乎的是能不能再分的细致点,当然,这样也能让项目有更低的耦合性,以及更高的复用性,下面看看组件的两种写法:

//函数式写法
function Welcome(props) {
  return 

Hello, {props.name}

; }
//es6写法
class Welcome extends React.Component {
  constructor(props){
    super(props)
    //使用了super才可以使用this 在constructor里
  }
  render() {
    return 

Hello, {this.props.name}

; } }

值得注意的是,使用es6写的的时候,如果想要在构造器中使用this,必须在之前使用super(props),至于为什么非得这么写,可以参考这篇文章https://blog.csdn.net/huangpb123/article/details/85009024

3、再看看他的生命周期
  • componentDidMount 组件渲染完成
  • componentWillUnmount 组件卸载前可以调用例如:清除定时器、监听
  • componentWillReceiveProps(nextProps) 父组件传给子组件props改变时使用,可以对比子组件的props,主要用于更新子组件
  • shouldComponentUpdate(nextProps,nextState) 组件更新前使用 return false可组织组件重新渲染
  • getSnapshotBeforeUpdate(nextProps,nextState)代替componentWillUpdate
  • componentDidUpdate(preProps,preState) 每次更新都会走这里,可以拿到更新前的状态值
4、事件

当你在使用类的方式写组件的时候,这时候要注意绑定事件的方法,必须在constructor里为事件绑定this,因为直接调用事件的话,这时候打印this,可以看到是undefined,我们可以在constructor里拿到传递给我们的值,所以在这里绑定上this



  constructor(props) {
    super(props)
    this.changeTemp = this.changeTemp.bind(this)
  }
  changeTemp(e) {
    console.log(this)
    this.props.onTempChange(e.target.value)
  }

解决方案,把方法写成函数表达式的形式

changeTemp=(e)=> {
    console.log(this)
    this.props.onTempChange(e.target.value)
}
5、根据条件渲染dom,以及绑定样式
{this.state.itemList.length > 0 &&

Name Price

}
{this.state.itemList}
6、为表单绑定事件

一:每个input绑定一个事件,这种弊端是每个方法都得重新在构造器绑定



二:多个input用同一个方法,根据他们的name来区分到底是哪个input,这种方法弊端是如果多个input公用一个方法,那么这一个方法过于臃肿,层次不够清晰

inputChange(e){
    const value = e.target.name == 'searchTxt' ? e.target.value : e.target.checked
    this.props.inputChange(e.target.name,value)
}

你可能感兴趣的:(React起步)