【问题标题】:ReactJS How to pass iterated values to child component from parent component using Context APIReactJS如何使用Context API将迭代值从父组件传递给子组件
【发布时间】:2021-01-04 12:57:12
【问题描述】:

如何使用 Context API 而不是通过 props 通过父组件将值传递给循环子组件。

父组件

import React, { useState } from 'react'
import { ChildComponent } from './child-component'
import parentContext from './ParentContext'

export function ParentComponent(props) {
const [ parentState ] = useState([
  {
    "name": "Jonny",
    "age": "20"
  },
  {
    "name": "Raj",
    "age": "24"
  },
  {
    "name": "Rahul",
    "age": "21"
  },
  {
    "name": "Jenny",
    "age": "26"
  }
])
return (
<parentContext.Provider value={{parentState: parentState}}>
{parentState.map((obj, index) => 
<ChildComponent
        name={obj.name}  
        index={index}
        age={obj.age}
    />
)}
</parentContext.Provider>
)
}

子组件

import React, { useState, useContext } from 'react'
import parentContext from './ParentContext'

export function ChildComponent(props) {
const parentData = useContext(parentContext)
const [ childState, setChildState ] = useState(parentData)
return (
<div className='container'>
<span>Name: {childState.name}</span>
<span>Age: {childState.age}</span>
</div>
)
}

我想从父组件传递值并将其发送到子组件,然后在子组件中显示值。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 在这种情况下你真的不需要context。你已经拥有的就好了。将 props 从父级传递给直接子级并没有错。
  • 同样在您的子组件中,您不需要将上下文的值存储在状态中。请注意,childStateparentData 将是一个数组。所以parentData[0]等将是每个元素。

标签: reactjs react-context


【解决方案1】:

实际上您不需要使用context 来实现上述目的,只需将您的组件更改为:

Parent

import React, { useState } from "react";
import { ChildComponent } from "./child-component";

export function ParentComponent(props) {
  const [parentState] = useState([
    {
      name: "Jonny",
      age: "20",
    },
    {
      name: "Raj",
      age: "24",
    },
    {
      name: "Rahul",
      age: "21",
    },
    {
      name: "Jenny",
      age: "26",
    },
  ]);

  return (
    <>
      {parentState.map((obj, index) => (
        <ChildComponent
          key={index}
          name={obj.name}
          index={index}
          age={obj.age}
        />
      ))}
    </>
  );
}

Children:

import React from "react";

export function ChildComponent({ name, age }) {
  return (
    <div className="container">
      <span>Name: {name}</span>
      <span>Age: {age}</span>
    </div>
  );
}

如果parentState 不会改变,最好只使用普通变量,如下所示:

const parentState = [
    {
      name: "Jonny",
      age: "20",
    },
    {
      name: "Raj",
      age: "24",
    },
    {
      name: "Rahul",
      age: "21",
    },
    {
      name: "Jenny",
      age: "26",
    },
  ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多