简体   繁体   中英

React - passing props to a component recieved in props

I'm using react and I am faced with a problem.

I have a component that needs to accept another component as prop, and pass into the same component other props. Example:

export default class Item extends React.Component {
    render() {
        return (<div onClick={this.props.onClick}>Some content.</div>)
    }
}

Item.propTypes = {
    onClick: PropTypes.func.isRequired
}

export default class Container extends React.Component {
    onClick() {
        // Do something.
    }
    render() {
        // render here the item and passing it my onClick method.
    }
}

Container.propTypes = {
    item: PropTypes.element.isRequired
}

Edit: So I probably can use the es5 syntax and do something like this:

React.createElement(item, {
    onClick: this.onClick
});

But how can I achieve that in es6?

This is what you need to do, if you need to pass all props, you can use spread operator too.

export default class Item extends React.Component {
  render() {
    return (
      <div onClick={this.props.handleClick}>Some content.>
      </div>
      )
  }
}

Item.propTypes = {
  onClick: PropTypes.func.isRequired
}

export default class Container extends React.Component {

  render() {
    const handleClick = () => {
      // Do something.
    }
    // render here the item and passing it my onClick method.
    render () {
      return (
        <Item handleClick={handleClick} />
      );
    }
  }
}

Container.propTypes = {
  item: PropTypes.element.isRequired
}

You need to pass in to Container, the Item component type and the props you want to assign instead of an instance. This is so that you can add more props before creating the instance

Then you can do like so:

class Container extends React.Component {
    static propTypes = {
        ItemType: PropTypes.func.isRequired,
        itemProps: PropTypes.object.isRequired,
    };

    onItemClick = () => {
       // do something
    };

    render() {
        const { ItemType, itemProps } = this.props;
        return <ItemType {...itemProps} onClick={this.onItemClick} />;
    }
}

class MyDisplay extends React.Component {
    render() {
        const ItemToRender = someCondition ? Item : AnotherItem;
        return <Container ItemType={ItemToRender} itemProps={{a: 1, b: 2}} />;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM