【React基础三】组件传值、高阶组件、Hook

1. 组件传值

1.1 概述

父组件向子组件传值(自定向下)可以直接使用props完成

<List ref={
    
    this.ref} {
    
    ...this.state.list[0]}/>

而子组件向父组件传值是自底向上的,这种操作react内部是不支持直接操作的,我们可以选择使用函数props来完成需求

通过在父组件引入的子组件中传递一个函数并传参,子组件去触发这个函数更改参数完成数据更新

1.2 子组件

	const List = React.forwardRef((props,ref)=>{
    
    
           const userNameClickFun=(name)=>{
    
    
                props.getUserName(name)
            }
            return <div ref={
    
    ref} className="list">
                <div onClick={
    
    ()=>{
    
    userNameClickFun(props.name)}} className="left"></div>
                <div className="right">
                    <div className="info">{
    
    props.name}</div>
                    <div className="text">{
    
    props.text}</div>
                </div>
             </div>
        })

1.3 父组件

 getUserNameFun(name){
    
    
     console.log(name)
 }
render(){
    
    
    return <div className="comment-box">
            {
    
    
            this.state.list.map(v=><List getUserName={
    
    this.getUserNameFun} key={
    
    v.id} {
    
    ...v}/>)
            }
            <div className="inp">
                <textarea ref="inpDom" onChange={
    
    (e)=>{
    
    this.getText(e)}}></textarea>
                <div>
                	 <button onClick={
    
    ()=>{
    
    this.subFun()}}>提交评论</button>
                </div> 
            </div>
		</div>
}

2. 高阶组件

如果一个函数操作其他函数,将其他函数作为参数或将函数作为返回值,将其称为高阶函数。高阶组件类似于高阶函数,接收 React 组件作为输入,输出一个新的 React 组件。高阶组件让代码更具有复用性、逻辑性与抽象特征。可以对 render 方法作劫持,也可以控制 props 与 state。
简单来说,高阶组件只是一个包装了另外一个 React 组件的 React 组件

		const NavTitle=(props)=>{
    
    
           return props.type===1?<h1>{
    
    props.title}</h1>: <h2>{
    
    props.title}</h2>
        }

        const Nav = (props)=>{
    
    
            if(props.type!=1&&props.type!=2){
    
    
                return <p>{
    
    props.title}</p>
            }else{
    
    
                let newPro={
    
    
                    ...props,
                    title:'高阶标题'+props.title
                }
                return <NavTitle {
    
    ...newPro}/>
            }
        }

3. Hook

使用函数声明的组件大多数为无状态组件,展示型组件一般是无状态组件

Hook是供给函数组件进行状态管理的方法,只能在 React 的函数组件中调用 Hook

3.1 State Hook

通过useState申明一个值为0的变量,并且同时可以获得一个可以更改当前变量的方法,通过setCount方法修改的count可以同时更新页面。等价Class组件的statesetState

function Example() {
  // 声明一个叫 "count" 的 state 变量
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

3.2 Effect Hook

useEffect简单理解就是监听函数组件中的数据。是componentDidMountcomponentDidUpdatecomponentWillUnmount 这三个函数的组合

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

猜你喜欢

转载自blog.csdn.net/qq_39335404/article/details/135050703