javascript 如何将数组从一个子组件传递到另一个子组件?

dpiehjr4  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(155)

如您所见,我有三个组件,第一个是Header,我想在其中获取arr
第二个组件是CardBox,我在其中创建了一个arr
我是新来的,据我所知我已经试过了

import React from 'react';
import { View, Text } from 'react-native';

const Header = () => {
  return (
    <View>
      <Text>Header</Text>
    </View>
  );
};

const CardBox = () => {
  const arr = ["A", "B", "C"]
  return (
    <View>
      <Text>CardBox</Text>
      <Text>arr in CardBox{arr}</Text>
    </View>
  );
};

const App = ({arr}) => {
  return (
    <View>
    <Text>arr in Home {arr}</Text>
      <View>
        <Header />
      </View>
      <View>
        <CardBox arr={arr}/>
      </View>
    </View>
  );
};

export default App;
9wbgstp7

9wbgstp71#

你可以通过在你的父组件中创建数组并将该数组作为 prop 传递给你的子组件来实现这一点。

import React from 'react';
import { View, Text } from 'react-native';
import { useSelector } from 'react-redux';

const Header = (props) => {
  const { arr } = props;

  //you can use use selector hook to get the arr from you redux store like this.
  //change your reducer name.
  const arrFromRedux = useSelector((state) => state.reducerName.arr);
  return (
    <View>
      <Text>Header</Text>
      <Text>arr in Header{arr}</Text>
      <Text>arr from redux in Header{arrFromRedux}</Text>
    </View>
  );
};

const CardBox = (props) => {
  const { arr } = props;
  //you can use use selector hook to get the arr from you redux store like this.
  //change your reducer name.
  const arrFromRedux = useSelector((state) => state.reducerName.arr);
  return (
    <View>
      <Text>CardBox</Text>
      <Text>arr in CardBox{arr}</Text>
      <Text>arr from redux in Header{arrFromRedux}</Text>
    </View>
  );
};

const App = () => {
  const arr = ['A', 'B', 'C'];
  return (
    <View>
      <Text>arr in Home {arr}</Text>
      <View>
        <Header arr={arr} />
      </View>
      <View>
        <CardBox arr={arr} />
      </View>
    </View>
  );
};

export default App;

希望你得到答案了。

相关问题