3

父组件,我通常会将一个函数作为道具传递给子组件

import React, { Component } from 'react';
import ListExampleSelectable from './List';


export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      childValue: '',
    };
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(event) {
    this.setState({
      childValue: event
    })
  }


  render() {
    return (
      <div>
        // I would usually just pass in a function here to handle the data 
        <ListExampleSelectable someFunction={this.handleClick} />
      </div>
    );
  }
}

子组件,在这里我通常会调用传递的函数并返回数据,但由于它是一个 HOC 组件,我收到错误消息“_this.props.someFunction 不是函数”,但我不知道为什么?

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {List, ListItem, makeSelectable} from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
import Subheader from 'material-ui/Subheader';

let SelectableList = makeSelectable(List);

function wrapState(ComposedComponent) {
  return class SelectableList extends Component {
    static propTypes = {
      children: PropTypes.node.isRequired,
      defaultValue: PropTypes.number.isRequired,
      someFunction: PropTypes.func,
    };

    // I added the constructor in here because I was not sure why it was removed thinking that was why the component was not receiving the props???
    constructor(props) {
      super(props)
    }

    componentWillMount() {
      this.setState({
        selectedIndex: this.props.defaultValue,
      });
    }

    handleRequestChange = (event, index) => {
      this.setState({
        selectedIndex: index,
      });
      // this works when the child component is just a normal component and not an HOC component????
      this.props.someFunction(event);
    };

    render() {
      return (
        <ComposedComponent
          value={this.state.selectedIndex}
          onChange={this.handleRequestChange}
        >
          {this.props.children}
        </ComposedComponent>
      );
    }
  };
}

SelectableList = wrapState(SelectableList);

const ListExampleSelectable = () => (

    <SelectableList defaultValue={3}>
      <Subheader>Selectable Contacts</Subheader>
      <ListItem
        value={1}
        primaryText="Brendan Lim"
        leftAvatar={<Avatar src="images/ok-128.jpg" />}
        nestedItems={[
          <ListItem
            value={2}
            primaryText="Grace Ng"
            leftAvatar={<Avatar src="images/uxceo-128.jpg" />}
          />,
        ]}
      />
      <ListItem
        value={3}
        primaryText="Kerem Suer"
        leftAvatar={<Avatar src="images/kerem-128.jpg" />}
      />
      <ListItem
        value={4}
        primaryText="Eric Hoffman"
        leftAvatar={<Avatar src="images/kolage-128.jpg" />}
      />
      <ListItem
        value={5}
        primaryText="Raquel Parrado"
        leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />}
      />
    </SelectableList>

);

export default ListExampleSelectable;
4

0 回答 0