美文网首页
react学习之hooks篇

react学习之hooks篇

作者: 洛梓煕 | 来源:发表于2020-04-24 14:16 被阅读0次

写无状态(函数)组件的时候会应用到,使函数组件变成有状态组件

const Fn=(props )=>{

    //通过props接收父组件传递过来的值,也可以接受父组件的方法从而改变原始props的值

return <div>{this.props.xx}</div>

export default Fn


useState的使用

const [count//定义一个变量,setCount//通过这个方法可以改变此变量]=usestate(data//初始值)

例子: 通过setCount方法实时改变count的值来渲染dom

子组件

importReact, {useState}from"react";

constFnComponent= (props)=>{

    let  [count,setCount] =useState(props.value);

    let countNew=0;

    constsetCountNew= ()=>{

    countNew+=1;

};

return(

    <div>

        <div>{props.value}</div>//父组件传递过来的值

        <div>{count}</div>//通过setCount的函数实时改变

        <div>{countNew}</div>//无论如何都不会被改变

        <buttononClick={()=>setCount(count+1)}>

            自身组件变量改变(用useState)

        </button>

        <buttononClick={()=>setCountNew()}>

            自身组件变量改变(未用useState)

        </button>

        <button

            onClick={()=>{

                props.fn(10);//父组件传递过来的方法从而改变this.props中的初始值

            }}

            >

            执行父组件传过来的方法

            </button>

    </div>

);

};

exportdefaultFnComponent;

父组件

state={

    test:0

}

changeTest= (val)=>{

        lettest= (this.state.test+=val);

        this.setState({

            test,

        });

    };

<FnComponentvalue={this.state.test}fn={this.changeTest}/>


useEffect的使用

useEffect包含了三个生命周期componentDidMount,componentDidUpdate 和 componentWillUnmount在初始化组件的时候需要做的事

例子:

useEffect(()=>{

    //在组件初始化的时候或者第二个参数发生更新的时候做的事

},[data1,data2])//在[]中data1或者data2发生改变的时候才会执行,可选参数

importReact,{useState,useEffect}from'react';

functionExample(){

     const[count,setCount]=useState(0);    

     useEffect(()=>{    document.title=`You clicked${count}times`; });

 return(

   <div>

         <p>You clicked{count}times</p>

         <buttononClick={()=>setCount(count+1)}>

            Click me

         </button>

   </div>

 );

}

相关文章

  • react学习之hooks篇

    写无状态(函数)组件的时候会应用到,使函数组件变成有状态组件 const Fn=(props )=>{ //通...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • 十个案例学会 React Hooks

    在学会使用React Hooks之前,可以先看一下相关原理学习React Hooks 前言 在 React 的世界...

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • React Hooks

    前言 React Conf 2018 上 React 提出了关于 React Hooks 的提案,Hooks 作为...

  • React学习系列之 React Hooks

    React Hooks React 16.8、useState、 React 16.8.0 is the firs...

  • 5分钟简单了解React-Hooks

    首先附上官网正文?:React Hooks Hooks are a new addition in React 1...

  • react-hooks

    react-hooks react-hooks 是react16.8以后,react新增的钩子API,目的是增加代...

  • React-hooks API介绍

    react-hooks HOOKS hooks概念在React Conf 2018被提出来,并将在未来的版本中被...

  • React Hooks 入门

    React Hooks 是 React v16.8 版本引入了全新的 API。 React Hooks 基本概念 ...

网友评论

      本文标题:react学习之hooks篇

      本文链接:https://www.haomeiwen.com/subject/vaymectx.html