简体   繁体   中英

How to Pass props in React component?

I am using reactjs. I have a componnt that is written like this:

import MyComponent from './Component';


 const test = [
    {
      id: '1',
      Component: FirstComponent,
    },
    {
      id: '2',
      Component: MyComponent,
    },
  ];

  return (
    <Demo
      components={test} 
    />
  );

In this case How can I pass props for MyComponent ?

If you need to pass additional props on to MyComponent then you should define an anonymous component in the config so you can pass new props to the child component. Don't forget to also pass props on through to the child component.

const test = [
  {
    id: '1',
    Component: FirstComponent,
  },
  {
    id: '2',
    Component: (props) => (
      <MyComponent {...props} prop1={prop1} prop2={prop2} etc />
    ),
  },
];

Firstly i want to introduce what is props. props means property that you are passing though your jsx code to functions or we can say pure functions. let me give you a demo with small element like H1 Tag.

I am creating a h1.js File.

import React from 'react';

// arrow function that get props
const H1 = (props) => {
     return '<h1>{props.text}</h1>';
}
export default H1;

Now when you want to use this function just import and pass though props like

#Main.js

import React from 'react';
import H1 from './h1.js';
class Main extends React.Component{
   constructor() {
     super();
   }
   render(){
     return(
        <>
          <H1 text="pass what you want"></H1>
        </>
     );
   }
}

so may be you will get idea how it work right;)

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