从子组件调用父组件中的函数 - React+flux+alt

Calling a function in parent component from a child component - React+flux+alt

我在我的反应中使用 flux+alt+es6 结构application.I想用我的子组件详细信息更新父状态。

父函数:

handleChange(name, e) {
    const change = {};
    change[name] = e.target.value;
    this.setState(change);
    console.log('---state:--', this.state);
  }

子组件:

import React from 'react';
import { Input, Button, Glyphicon } from 'react-bootstrap';

export default class TextBoxesSet extends React.Component {
  constructor(props) {
    super(props);
  }
  _onRemoveName = (id) => {
    this.props.name.slice(id, 1);
  }
  static getPropsFromStores() {
    return {name: 'en', description: '', AttributeSectionName: []};
  }

  render() {
    return (
      <div >
        <div className="">
          <Input type="select" placeholder="select" wrapperClassName="col-xs-4"
          value={this.props.name} onChange={this.handleChange.bind(this, 'name')} >
            <option value="one">One</option>
            <option value="two">Two</ption>
            <option value="three">Three</option>
          </Input>
        </div>
        <div className="col-md-1">
          <Button bsSize="small"><Glyphicon glyph="remove" onClick={this._onRemoveName} /></Button>
        </div>
      </div>
    );
  }
  handleChange(name, e) {
    ParentComponent.handleChange(name, e);
  }
}
TextBoxesSet.propTypes = {
  name: React.PropTypes.object,
  description: React.PropTypes.object,
  AttributeSectionName: React.PropTypes.arrayOf(React.PropTypes.object)
};

如何从子组件访问父组件中的函数?

你把它作为道具传递,f.ex:

<TextBoxesSet handleChange={this.handleChange} />

然后:

this.props.handleChange(name, e);

您还需要将其添加为 propType:

handleChange: React.PropTypes.func

如果您需要在函数中访问 this,您可能还需要在父构造函数中绑定正确的上下文:

this.handleChange = this.handleChange.bind(this)