简体   繁体   中英

Access variable on child from parent in react.js

I am trying to get access to a variable "Name" in my child class from my parent class. I am using react routers on this project. I've been using React for a few days, so I am open to any suggestions or refactoring.

Child class:

import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';

export default React.createClass({
render: function() {
    return (
       <ul className="list">
            {this.props.business.map(function(business, i) {
                    let Name = Object.keys(business).length - 1;
                    return (
                        <li key={business.id}>
                            <Link to="/" className="inner">
                                <div className="li-img">
                                    <img src={business.image} alt="Image Alt Text" />
                                </div>
                                <div className="li-text">
                                    <h4 className="li-head">{business.name}</h4>
                                    <p className="li-sub">Summary of content</p>
                                </div>
                            </Link>
                       </li>
                    );
                })}
        </ul>
    )
}
});

Parent Class:

import React from 'react';
import Business from './businesses';
import { getBusiness } from 'api/global';

export default React.createClass({
  getInitialState: function() {
    return {
        business: [],
    }
},
  componentWillMount: function() {
      var _this = this;
       getBusiness().then(function(response) {
          _this.setState({
            business: response.data
        })
    }).catch(function(err) {
        console.error(err);
    });
},

  render: function() {
    return (
        <Business business={this.state.business} text={Name} />
    )
   }
});

I don't think you can do, directly, what you are attempting here.

At the time that you render Business you need to know the values that you want to pass to it. Your "construct" is just like asking "I want to pass a parameter to a function that is calculated by the function that I am calling".

Communication between components gives you a hint at what is needed: some event that causes a re-render after the new value ( Name ) has been computed.

This could be by the Business updating a state variable Name , which would cause a re-render, or by passing in a callback (as the example shows).

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