将props中的函数传递给组件

时间:2017-01-15 09:49:19

标签: reactjs

我有新的反应并试图将全局函数传递给组件,以避免在每个组件中重复它。这不起作用,当我尝试在组件中调用它时,我得到一个未定义的错误。

这是我的代码:

import React from 'react';
//components
import League from './League';
class App extends React.Component {

state = {
    leagues: {},
};

componentDidMount() {
    this.getLeagues();
}

get(url) {
    var myHeaders = new Headers();
    myHeaders.append("Accept", "application/json");
    myHeaders.append("X-Mashape-Key", "mysecretkeyblablabla");
    var myInit = 
        {
            headers: myHeaders
        };

    return fetch(url,myInit)
    .then(function(response) {
        if(response.ok) {
            return response.json().then(function(json) {
                return json.data;
            });
        }
    });
};

getLeagues() {
    this.get('https://sportsop-soccer-sports-open-data-v1.p.mashape.com/v1/leagues').then((data) => {
        this.setState({leagues: data.leagues});
    });
}

render() {

    const leagues = Object
                        .keys(this.state.leagues)
                        .map(key => <League get={this.get} key={key} details={this.state.leagues[key]} />
                     );

    return(
        <div className="App">
            <div className="App-header">
                <h1>Welcome to Foot Stats app (made in ReactJS)</h1>
            </div>
            <p className="App-intro">
                Here is the place where I should put the countries.
            </p>
            <ul>
                {leagues}
            </ul>
        </div>
    );
};
}

export default App;

和我的联盟组件

import React from 'react';
import Season from './Season';

class League extends React.Component {

state = {
    seasons: {},
};

constructor(props) {
    super(props);
}

componentDidMount() {
    //this.getSeasonsAvailable(this.props.details.league_slug);
}

getSeasonsAvailable(league) {
    const url = 'https://sportsop-soccer-sports-open-data-v1.p.mashape.com/v1/leagues/{league_slug}/seasons'.replace('{league_slug}',league);
    const seasons = [];
    console.log(this.props);
    this.props.get(url).then((data) => {
        data.seasons.map(function(object, i) {
            seasons[data.seasons[i].identifier] = data.seasons[i];
        });
        this.setState({seasons: seasons});
    });
};

render() {
    const seasons = Object
                        .keys(this.state.seasons)
                        .map(key => <Season key={key} league_slug={this.props.details.league_slug} details={this.state.seasons[key]} />
                     );
    return (
        <li>
            <span onClick={this.getSeasonsAvailable.bind(this.props.details.league_slug)}>{this.props.details.nation} : {this.props.details.name}</span>
            <ul>
                {seasons}
            </ul>
        </li>
    );
}

static propTypes = {
    get: React.PropTypes.func.isRequired  
};
}

export default League;

当我点击季节组件时,我收到此错误:

  

无法阅读财产&#39; get&#39;未定义的

我的console.log(this.props)会给我undefined

谢谢!

2 个答案:

答案 0 :(得分:1)

您只需要更改

<span onClick={this.getSeasonsAvailable.bind(this.props.details.league_slug)}>

<span onClick={this.getSeasonsAvailable.bind(this, this.props.details.league_slug)}>

除此之外,如果您想使用ES6方式执行此操作。您可以使用arrow functions

<span onClick={() => this.getSeasonsAvailable(this.props.details.league_slug)}>

或者您可以使用

bind构造函数中的getSeasonsAvailable函数
constructor() {
    super();
    this.getSeasonsAvailable = this.getSeasonsAvailable.bind(this);
}

您可以详细了解herehere

答案 1 :(得分:0)

因为您的onClick:.bind(this.props.details.league_slug)

实际上this.props.details.league_slug是什么?

bind会更改thisgetSeasonsAvailable的引用(this将引用this.props.details.league_slug,我不知道它是什么),当然,当你致电this.props

时,你会得到不确定的

只需.bind(this),因此this中的getSeasonsAvailable可以引用该组件本身。