React核心知识点

React核心知识点

介绍

react是最近很是流行的框架,相对于vue框架,对js、es6以及以上的版本的语法要求会更高。核心是把设计好的UI划分成组件层级。

JSX的使用

js是JavaScript的语法扩展。在编译的时候JSX表达式会被转为不同js对象,所以把jsx表达式嵌入if语句或者for 也都是没有问题的.

# 基本表达式
  const element = <h1>Hello World!</h1>
# 嵌入函数中,编译成为函数组件
function geGretting(){
    return <h1>Hello Gretting </h1>;
}
# JSX使用特定属性
const element = <img src={img.url} />

 # jsx 表示对象
 const el = (
 <h1 className = "greeting">
   Hello World!
 </h1>
 )
 
 React.createElement(
 'h1',
 {classNmae:'greeting'},
 'Hello World!'
 )

函数组件和class组件

# 函数组件
function Welcome (){
    return <h1>Hello World!</h1>
}
# class组件
class  Welcome extends React.Component{
    render(){
        return (
        <h1>Hello World</h1>
        );
    }
}

父子组件之间通信

父组件向子组件传值

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

class Parent extends React.Component{
     render(){
         return(
           <Child name="www1"></Child>;
           <Child name="www2"></Child>;
         )
     }
 }

子组件向父组件传值

class Child  extends React.Component{
    constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);  //重要操作
  }
 function handleChange(e){
     this.props.handleParent(e.target.value)
 }
   render(){
    return (
       <input onChange={this.handleChange} ></input>
       )
    }
}

class Parent extends React.Component{
   constructor(props) {
    super(props);
    this.onHandle = this.onHandle.bind(this);  //重要操作
  }
  function onHandle(value){
      console.log("最终获取到从子组件传进的参数")
  }
     render(){
         return(
           <Child handleParent={this.onHandle}></Child>;
         )
     }
 }

Hook特性

Hook是react新增的一个属性,在不编写class组件的时候使用其他React的特性。

  • 特性一:count属性相当于 this.state.count
function Example(){
    const [count,setCount] = useState(0) //初始化count为0
    return (
    <div >{count}</div>
    <button onClick ={()=>{setCount(count+1)}} ></button>
    )
}
#等价与如下
class Example extends React.Component{
    constructor(props){
        super(props);
        state={ count:0};
    }
    render(){
        return (
        <div >{count}</div>
        <button onClick ={()=>{this.setState({count:count+1)}) } ></button>
        )
    }
}

注意点:

  • props的内容不可更改
  • 组件名首字母大写
  • 在return的内容最外层必须要有一个div大标签,或者用 <React.Fragment></React.Fragment>包括在最外层
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,544评论 1 33
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 2,862评论 1 18
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,075评论 0 1
  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 8,112评论 2 35
  • 今天的React题没有太多的故事…… 半个月前出了248个Vue的知识点,受到很多朋友的关注,都强烈要求再出多些R...
    浪子神剑阅读 10,141评论 6 106