How to access Component properties into another component file

时间:2019-04-16 23:06:23

标签: reactjs

I'm new to react and i've been learning how to solve this error by Accessing properties of a component class to another component class.

import React, { Component } from 'react';
import People from './Properties/People';
import './App.css';

class App extends Component {

// Here I'm trying to access props from People component and print it out.

    <div className='one'>
            <h1> Bunch of People </h1>
            <p> The name is {this.state.Names[1].Person2} </p>
            <p> The name is {this.state.Names[2].Person3} </p>
            <p> The name is {this.state.Names[0].Person1} </p>
          </div>
        );
      }
    }

export default App;

./Properties/People

import { Component } from 'react';

class People extends Component{
constructor(){
    super();
this.state = {
        Names: [
        { Person1: 'Hetch' }, 
        { Person2: 'Danny' }, 
        { Person3: 'Willy' },
        { Person4: 'Tiget' }, 
        { Person5: 'Leclerc'}, 
        { Person6: 'Zoel' }]
}}
}
export default People;


Compiled with warnings.

./src/App.js
  Line 2:  'People' is defined but never used  no-unused-vars

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

1 个答案:

答案 0 :(得分:0)

The way react shares data between components is by props , which is an object. So you need to call your App component inside your People component and pass the state as props. Try this inside your people component

<App people={this.state.Names} />

And call this.props.people inside your App component and you will get the Names

more info: https://reactjs.org/docs/components-and-props.html

Hope this help!

相关问题