简体   繁体   中英

How to pass a list of props to a component

I have defined by array of props like following

Footer.propTypes = PropTypes.arrayOf(
  PropTypes.content({
    title: PropTypes.string,
    click: PropTypes.func
  })
)

How i can now create a const which initialise this props array and than pass it to a component.

Let's assume you have components name like UserInfo

pass multiple props to components like if you have an array like

let arr = [{ title: "", click: "" }, {title: "", click: ""}]
<UserInfo fname={"Xyz"} lname={"Pqr"} designation={"Developer"} arrData={arr} />

in your UserInfo component you can get in render or any methods like

let fname = this.props.fname;
let lname = this.props.lname;
let designation = this.props.designation;
let arrData = this.props.arrData;

or

let { fname, lname, designation, arrData } = this.props;

I think one of the easiest ways is to create a JSON in parent, and access from child to keys like this:

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  constructor() {
    super();
    this.state = {
      obj: {
        name: "Joe",
        age: 15,
        email: "joe@gmail.com"
      }
    };
  }
  render() {
    return (
      <div>
        <Child obj={this.state.obj}/>
      </div>
    );
  }
}

function Child(props) {
  return (
    <div>
      {props.obj.name}<br/>
      {props.obj.age}<br/>
      {props.obj.email}
    </div>
  )
}

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM