简体   繁体   English

React-将props传递给props中接收的组件

[英]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: 编辑:所以我可能可以使用es5语法并执行以下操作:

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

But how can I achieve that in es6? 但是如何在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. 您需要传递给Container,要分配的Item组件类型和prop而不是实例。 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}} />;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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