React 官方文档摘录

102 阅读2分钟

渲染到屏幕的流程

  1. 在html中添加元素 div#root
  2. 在JS中获取该元素
  3. JSX语法编写组间函数
  4. 用ReactDOM.render(module,element)将组建渲染到html元素中

React 认为渲染逻辑本质上与其他 UI 逻辑内在耦合。

JSX语法

1. 嵌入表达式 <h1> {formatNum(count)} </h1>
2. 指定属性 	 <img src={avatarURL}></img>
3. 指定子元素	 
	import {App} from './app.js'
	<div> 
		<App/> 
	</div>

组件通信

1. 子组件中,接受函数参数 function Children(props){ return props.name }
2. 父组件中,通过属性key:value来传递参数 
	<App>
		<Children name="zs" />
	</App>
3. props是不可变的,但是state是变化的、动态的

类的生命周期

  1. componentDidMount 挂载
  2. componentWillUnmount 销毁

单向私有 state两种更新方式

1. this.setState({date: new Date()});
2. this.setState(()=>{
      return {date: new Date()}
   })

事件处理

  1. 声明形式:
constructor(){
    this.sayHello = this.sayHello.bind(this);
}
sayHello(){ 
    console.log(`I'm say Hello :`, this);
}
<button onClick={this.activeLasers}> CKK ME </button>
  1. 在调用函数时,需要bind绑定this,否则函数中的this不会指向当前jsx类,而是undefined,如果不想入上所示绑定,可以采取在jsx组件中调用:
<button onClick={(e)=>this.activeLasers(id,e)}> CKK ME </button>
  1. 箭头函数下,事件对象e会被显示传递,如果通过bind绑定,则进行隐式传递

条件渲染

  1. 通过if判断
if(condition){ return component1 } else { return component2 };
  1. 三元表达式
render(){
    return (
       <div>
       {condition
         ? <Login />
         : <Logout />
       }
      </div>
    )
}
  1. && 运算符,会返回count的值,如果count=0,则返回<div>0</div>
<div> { count && <h1> Messages: {count} </h1> } </div>

通过useState直接修改内容

<span onClick={() => { setContent(<Login />) }}>登陆</span>
<span onClick={() => { setContent(<Logout />) }}>注销</span>
<div> {content} </div>

或上文的三元表达式

元素列表

  1. key的指定尽量靠近父元素
  2. 循环格式:
let list = ["pencil", "apple", "sugar", "banner", "wallmater"]
    return (
    <ul>
      {list.map((v, i) => {
        return <li key={i}>{v}</li>
       })
      }
    </ul>
)

表单

状态提升: 在子组件里 调用父组件的方法 修改父组件传递来的值

组件嵌套

采用 props.children 属性,和vue中的slot一样。

function Child(props){
    return (
        <div>
        {props.children} 
        // 默认是children,可以自定义
        </div>
    )
}

function Fat(){
    return (
        <Child>
            <h1> this is title </h1>
        </Child>
    )
}

codepen.io/gaearon/pen…

自定义组合

<div className="child" right={OtherComponent1} left={OtherCompoent2}>
</div>


function Child(props){
    return (
        <div>
            {props.left}
            {props.right}
        </div>
    )
}