React

·  阅读 117
react创建ref的方式

const Home = React.lazy(() => import("./view/Home")); 懒加载

 this.inputRef = React.createRef();

<input  ref={ this.inputRef } />

第二种方式,直接定义一个函数 ref={(btn) => {this.btnRef = btn}}
复制代码

react开发menu组件

//menu组件
import React, {useState, useEffect} from "react";
import MenuItem from "./MenuItem";
const Menu = (props: any) => {
    const [activeIndex, setActiveIndex] = useState(0)
        {
            React.Children.map(props.children, (child, index: number) => {
                return React.cloneElement(child, {
                    index: index,
                    activeIndex,
                    setItem(val: number) {
                        console.log('val', val)
                        setActiveIndex(val)
                    }
                })
            })
        }
    </div>
}
export default Menu

//menuItem组件
import React, {useState, useEffect} from "react";
const MenuItem = (props: any) => {
    console.log('props', props)
    const { activeIndex, index, children, setItem } = props
    
    const handleItem = (val: number) => {
        setItem(val)
    }
    return <>
        <div style={{color: activeIndex === index ? '#f00' : '#000', cursor: 'pointer'}} onClick={() => {handleItem(index)}}>{children}</div>
    </>
}

MenuItem.displayName = 'MenuItem'

export default MenuItem
复制代码
  • react通过React.Children获取所有的孩子节点
  • React.cloneElement 克隆节点,然后添加属性和方法,到子组件中
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改