React子组件的状态未定义

时间:2016-07-26 20:12:16

标签: javascript reactjs ecmascript-6

我有一个父组件PlanList:

class PlanList extends Component {
  constructor(props) {
    super(props);
    this.renderPlans = this.renderPlans.bind(this);
    this.planListFilter = <PlanListFilter onChange={this.handleFilterChange.bind(this)} />
  }

  loadPlans() {
    console.log(this.planListFilter);
    // returns: Object {$$typeof: Symbol(react.element), key: null, ref: null, props: Object, _owner: ReactCompositeComponentWrapper…}

    console.log(this.planListFilter.state);
    // returns: undefined
    // I expect it to return the state object i defined in the PlanListFilter constructor

    // here I would apply the filters to the PlanTable
  }

  handleFilterChange(event) {
    this.loadPlans();
  }

  render() {
    return (
      <div className="PlanList">
        {this.planListFilter}
        <PlanTable />
      </div>
    )
  }
}

和子组件,PlanListFilter:

class PlanListFilter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      search: '',
    };
    this.handleSearchChange = this.handleSearchChange.bind(this);
  }

  handleSearchChange(event) {
    this.setState({search: event.target.value});
    this.props.onChange(event);
  }

  render() {
    return (
        <FormControl type="text" placeholder="Search" onChange={this.handleSearchChange} value={this.state.search} />
    );
  }
}

更改FormControl上的文本时,会按预期触发onChange属性,但在父对象中,子项的stateundefined。我希望它会填充正确的状态。

1 个答案:

答案 0 :(得分:2)

在React数据流向一个方向,如果你的父母应该知道孩子的变化,你必须将一个处理程序作为一个道具传递给孩子,所以它将从孩子内部调用。

class Papa extends React.Component {
  constructor(p, c) { super(p, c) }
  handleFilterChange(valueFromChild) {
   //
  }
  render() {
     return <Child filterHandler={this.handleFilterChange} />
  }
}

const Child = ({filterHanlder}) => (
   <button onClick={() => filterHandler('valueToParent') } >Click Me</button>
)