React 面向组件编程 之 函数式组件

简单组件 和 复杂组件 的概念

如果组件有state(状态)属性,就是复杂组件

如果没有state(状态)属性,就是简单组件

state、props、refs是组件实例的三大核心属性,在之后会逐一进行详细地讲述,不了解者可以先跳过,之后再来回看下述内容。


函数式组件

function App() {
    return <h1>我是一个函数式组件</h1>
}

以上App函数式组件符合简单组件的定义,因为它没有state。

创建函数式组件,首字母必须大写,必须要有返回值。


函数式组件使用props

在React16.8.0版本之前,函数式组件只能使用三大组件中的props,其他两个属性都使用不了。

因此在16.8.0版本之前函数式组件注定只能是简单组件,应用远不如类式组件。

function App(props) {

    const { name, sex, age } = props;
    
    return <h1>我的名字叫做{name}, 性别{sex}, 今年{age}岁</h1>
}

// 将App组件标签渲染到index页面的div上
ReactDOM.createRoot(document.getElementById('root')).render(<App name="cxk" sex="女" age="18" />);

函数式组件中使用state

在16.8.0版本,React推出了新特性/新语法:Hook。

可以让你在函数组件中使用state以及其他的React特性,改变了函数组件拉胯的地位。

使用其中的 State Hook 可以让函数组件使用state。

useState:

import React, { useState } from "react";

export default function App() {

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

    return (
        <>
            <h1>点击了{count}次</h1>
            <button onClick={ () => setCount(count + 1) }>+1</button>
        </>
    )
}
  • 语法:
    • const [xxx, setXxx] = React.useState(initValue);// initValue是xxx的初始值,setXxxx是用来设置xxx值的函数
  • useState()说明:
    • 参数:第一次初始化的值
    • 返回值:第一个是内部当前的状态值,第二个是更新这个状态值的函数
  • setXxx()的2种写法:
    • setXxx(newValue):参数为非函数值,直接指定新的状态值,覆盖旧的状态值
    • setXxx(value => newValue):参数为函数,可以接收到原本的旧的状态值作为参数,函数的返回值newValue会覆盖旧的状态值

函数式组件中使用refs

使用其中的 Ref Hook 可以让函数组件使用refs。

useRef:

import React, { useRef } from "react";

export default function App() {

    const inputEl = useRef(null);

    const onButtonClick = () => {
        console.log(inputEl.current);
        inputEl.current.focus();
    }

    return (
        <>
            <input ref={inputEl} type="text" />

            <button onClick={onButtonClick}>Focus the input</button>
        </>
    )
}
  • 语法:
    • const inputEl = useRef(initialValue) // useRef返回一个可变的ref对象,对象的current属性初始化为initialValue

如果input不是个普通的dom元素,而是个组件,该怎么办呢?

使用forwardRef将input封装成一个组件TextInput。

import React, { useRef, forwardRef } from "react";

const TextInput =  forwardRef((props, ref) => {
    return <input ref={ref} type="text"></input>
});

export default function App() {

    const inputEl = useRef(null);

    const onButtonClick = () => {
        console.log(inputEl.current);
        inputEl.current.focus();
    }

    return (
        <>
            <TextInput ref={inputEl}></TextInput>

            <button onClick={onButtonClick}>Focus the input</button>
        </>
    )
}
posted @ 2022-09-21 10:00  笔下洛璃  阅读(328)  评论(0编辑  收藏  举报