通过道具反应传递数组

时间:2020-02-29 23:59:55

标签: reactjs

我有一个要传递给孙子组件的数组。

class App extends Component {
 constructor(props) {
  super(props);
    ...
  }

  componentDidMount() {
   array = ['a', 'b', 'c'];
  }

  render() {
   return (
    <Child arrayData={this.props.arrayData} />  ???
   )}

我知道我必须先通过道具将数据传递给孩子(然后从那里传递给孙子),但是如何格式化呢?那孩子如何获得道具呢?

2 个答案:

答案 0 :(得分:1)

这里是从父级到孙级数组中传递值的示例。请注意,称呼是如何在父项prop中声明和分配的,并通过子代传播给孙子。

可以轻松修改此示例,以传递整个数组而不是其中的单个值。

  render() {
    return (
      <div>
        <h1>Passing props through the component tree...</h1>
        <Parent greeting={salutations[0]}/>        
      </div>
    );
  }
}

const Parent = (props) => {
  return (
    <div>
      <h2>Parent</h2>
      <Child greeting={props.greeting} />
    </div>
  );
};

const Child = (props) => {
  return (
    <div>
      <h3>Child</h3>
      <Grandchild greeting={props.greeting} />
    </div>
  );
};

let salutations = ["hey", "what's up", "hello"]
const Grandchild = (props) => <h4>Grandchild - {props.greeting}</h4>;

ReactDOM.render(<App />, document.getElementById('app'));

答案 1 :(得分:1)

你好

亲爱的,您可以尝试使用此代码

import ClientImg1 from "../../assets/static/img/client/client_img_1.png";
import ClientImg2 from "../../assets/static/img/client/client_img_2.png";

const themes = {ClientImg1, ClientImg2};

render() {
   return (
    <Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/> 
   )
}

<Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/>

组件或功能页面

您可以使用此功能致电给他们 如果功能

function ClientSingleItem({arrayData1,arrayData2}) {
    return (
       <img src={arrayData1} alt="ClientImg" />
       <img src={arrayData2} alt="ClientImg" />
       .....
    )
}