React 组件

  • 组件是元素复用的思想,也是组件化框架的最主要的特征。我们现在要把网页的菜单栏看出一个组件,然后独立的抽象出来,这样做之后,任何需要菜单的页面只要导入该组件,就可以实现代码复用,让维护和扩展都变得简单。

组件有两个核心概念:

props

props 就是组件的属性,由外部通过 JSX 属性传入设置,一旦初始设置完成,就可以认为 props 是不可更改的,所有 React 组件都必须像纯函数一样保护它们的 props 不被更改。 1.父组件提供一个回调函数(用于接收数据) 2.将该函数作为属性的值,传递给子组件 3.子组件通过props调用回调函数

Parent.js:

import React, { useState } from 'react';
import Child from './Child';
export default function Parent(){
    const getChi1dMsg=(msg) =>{
     console.1og("接收到子组件数据" ,msg)
    }
    return (
       <div>
        <Child getMsg={getChildMsg}/>
      </div>

    );
}

Child.js


import React, { useState } from 'react';
export default function Child(props) {
  const [state, setState] = useState("11111");
  const handleclick=() =>{
      // 子组件调用父组件中传递过来的回调函数
      props.getMsg(state)
    }
  return ( 
    <div>
        <button onclick={handleclick}>点我,给父组件传递数据</button>
    </div>
   )
})
powered by GitbookEdit Time: 2024-06-06 18:25:41