在React中传递状态更新程序clickHandler

时间:2017-06-02 18:22:24

标签: javascript reactjs

我有一个React应用程序,如:

Main.js -

import React, { Component } from 'react';
import _ from 'underscore';

import ApplicationsButtons from '../components/ApplicationsButtons';


let applications_url = 'http://127.0.0.1:8889/api/applications'


export default class Main extends Component {

  constructor(props) {
      super(props);
      this.state = {applications: [], selected_app: 1};
      this.updateSelectedApp = this.updateSelectedApp.bind(this);
  }

  componentDidMount() {
    let self = this;
    $.ajax({
        url: applications_url,
        method: 'GET',
        success: function(data) {
            console.log(data);
            let objects = data.objects;
            let apps = objects.map(function(object) {
                return {name: object.name, id: object.id};
            });
            console.log(apps);
            self.setState({applications: apps});
        }
    });
  }

  updateSelectedApp(id) {
      this.setState({selected_app: id});
  }

  render() {

    return (
      <div>
        {this.state.selected_app}
        <ApplicationsButtons apps={this.state.applications} />
      </div>
    );
  }
}

ApplicationsButtons.js -

import React, { Component } from 'react';


export default class ApplicationsButtons extends Component {

  render() {
    var buttons = null;
    let apps = this.props.apps;
    let clickHandler = this.props.clickHandler;
    if (apps.length > 0) {
        buttons = apps.map(function(app) {
            return (<button key={app.id}>{app.name} - {app.id}</button>);
            // return (<button onClick={clickHandler.apply(null, app.id)} key={app.id}>{app.name} - {app.id}</button>);
        });
    }

    return (
      <div>
        {buttons}
      </div>
    );
  }
}

我想将onClick传递给将更改当前所选应用的按钮。不知何故,我刚刚在React中获得了第一个无限循环(&#34; setState刚刚运行了20000次&#34;)。显然,当我试图传递事件处理程序以便在点击时调用时,我告诉它继续调用它。

onClick函数应更改state.selected_app组件的Main,具体取决于所点击按钮的id

1 个答案:

答案 0 :(得分:2)

您没有将处理程序作为prop传递。 这是你应该做的:

render() {
  return (
    <div>
      {this.state.selected_app}
      <ApplicationsButtons 
         apps={this.state.applications} 
         handleClick={this.updateSelectedApp}
      />
    </div>
  );
}

在ApplicationButtons中:

render() {
  var buttons = null;
  let apps = this.props.apps;
  let clickHandler = this.props.handleClick;
  if (apps.length > 0) {
    buttons = apps.map(app => 
      <button key={app.id} onClick={() => clickHandler(app.id)}>{app.name} - {app.id}</button>);
    );
  }

  return (
    <div>
      {buttons}
    </div>
  );
}