react浅探react父子组件通讯(函数组件为例)

Posted GHUIJS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react浅探react父子组件通讯(函数组件为例)相关的知识,希望对你有一定的参考价值。

父组件向子组件传递自定义属性(可以是方法、变量)

import React,FunctionComponent, useState,useEffect from 'react';


const Todo = () => 
    const [todoList,setTodoList] = useState([
        id:0,title:'吃饭',done:true,
        id:1,title:'睡觉',done:true,
        id:2,title:'打豆豆',done:false]);

    const add = (newItem) => 
        setTodoList([...todoList,newItem])
    

    const delItem = (index) => 
        setTodoList(todoList.filter((item,i) => i !== index))
    

    return (
       <div className="todo-content">
           <TodoHeader add=add  listLength=todoList.length />
           <TodoBody delItem=delItem list=todoList />
           <TodoFooter/>
       </div>)

子组件使用父组件传递的自定义属性(可使用变量,也可以调用方法)

import React,FunctionComponent, useState,useEffect from 'react';
import './index.css';

const TodoHeader:FunctionComponent = props => 
    const add, listLength = props;
    const addTodo = (event) => 
        const  keyCode, target  = event;
        if(keyCode === 13)
            add(id: listLength, title: target.value)
        
    
    return (
        <div className='todo-header'>
            <input type="text" onKeyUp=addTodo />
        </div>)

父组件执行子组件方法

子组件定义方法并抛出

import React,FunctionComponent,useImperativeHandle from 'react';

const TodoHeader:FunctionComponent = props => 
    const sayHi = () => 
        console.log('我是TodoHeader');
    

    useImperativeHandle(props.onRef,() => 
        return
            sayHi
        
    )

    return (
        <div className='todo-header'>
            <input type="text" onKeyUp=addTodo />
        </div>)

父组件获取子组件示例对象并调用子组件方法

import React,FunctionComponent,createRef from 'react';

const Todo = () => 
    const todoHeaderRef = createRef();

    const doChildFn = () => 
        todoHeaderRef.current.sayHi();
    

    return (
       <div className="todo-content">
           <button onClick=() => doChildFn()>按钮</button>
           <TodoHeader add=add onRef=todoHeaderRef listLength=todoList.length />
       </div>)

以上是关于react浅探react父子组件通讯(函数组件为例)的主要内容,如果未能解决你的问题,请参考以下文章

react浅探react函数组件与类组件

react浅探react函数组件与类组件

react.js 父子组件数据绑定实时通讯

React 组件间通讯

react 父子组件执行顺序

React7.组件间的通讯