zoukankan      html  css  js  c++  java
  • React父子组件传值

      父组件向子组件传值使用props,子组件向父组件传值通过触发方法来传值。具体栗子如下。

    一、创建父组件index

    import React, { useState } from "react";
    import { Input } from 'antd'
    import ChildComponent from "./ChildComponent"; 
    export default () => {
      const [inputValue1, setInputValue] = useState<string>('传递的第一个参数')
      return (
        <div>
          <div>
            <h2>父组件</h2>
            <Input style={{  '200px' }} placeholder='请输入内容' value={inputValue1} onChange={(e) => setInputValue(e.target.value)} />
          </div>
          <ChildComponent inputValue1={inputValue1}/>  //向子组件传递了一个inputValue1
       </div>
      );
    };

    二、创建子组件ChildComponent

    import React, { useState } from "react";
    import { Button } from "antd";
    export default (props: any) => {
      return (
        <div>
          <h2>子组件</h2>
          <p>inputValue1:{props.inputValue1}</p>  //通过props拿到了父组件传递的inputValue1
        </div>
      );
    };

    三、父组件向子组件传值

      父组件向子组件传值时,先将需要传递的值传递给子组件,然后在子组件中,使用props来接收父组件传递过来的值,具体的可看创建父子组件的代码。

      父组件将inputValue1传递给子组件:

    <ChildComponent inputValue1={inputValue1} />

      子组件通过props接收inputValue1:

    <p>inputValue1:{props.inputValue1}</p>

      这样在父组件的input改变时,子组件通过props获取的inputValue1也会实时改变。如:在父组件输入框输入“改变了父组件”,子组件也变成了“改变了父组件”。这样一个父组件向子组件传值就完成了。

      

     四、子组件向父组件传值

      子组件向父组件传值时,需要通过触发方法来传递给父组件

      父组件定义一个方法:

    <ChildComponent inputValue1={inputValue1} childClick={childClickFunc} />     //定义一个childClickFunc方法
    const childClickFunc = (value: any) => {
        //通过触发方法改变父组件的值   value即为子组件传递给父组件的值
        setInputValue(value) 
      }

      子组件触发父组件方法:

    <Button onClick={() => props.childClick('子组件改变父组件的inputValue')}>点击改变父组件的值</Button> //通过props触发父组件传递的方法

     点击Button按钮后,触发父组件方法,父子组件的值都更改为“子组件改变父组件的inputValue”,这样子组件向父组件传值就完成了。

     

     五、父组件向子组件传递多个值的写法

      父组件需要向子组件传递多个值,比如inputValue1,inputValue2,inputValue3.......

      方法1:

    <ChildComponent inputValue1={inputValue1} inputValue2={inputValue2} inputValue3={inputValue3} childClick={childClickFunc} />

      方法2:

    <ChildComponent {...{ inputValue1, inputValue2, inputValue3 }} childClick={childClickFunc} />

      两种写法都可进行传值,只是第二种比较简洁。

      

  • 相关阅读:
    ios 中的循环引用问题及解决
    Leetcode-Maximum Depth of Binary Tree
    Leetcode-Min Stack
    Leetcode-Intersection of Two Linked Lists
    Leetcode-Binary Tree Inorder Traversal
    Leetcode-Unique Binary Search Trees II
    Leetcode-Unique Binary Search Trees
    Leetcode-binary Tree Zigzag Level Order Traversal
    Leetcode-Construct Binary Tree from inorder and preorder travesal
    Leetcode-Next Permutation
  • 原文地址:https://www.cnblogs.com/minorf/p/12978688.html
Copyright © 2011-2022 走看看