ReactJS:将我自己的道具添加到另一个组件中

ReactJS: adding my own props to another component

本文关键字:添加 另一个 组件 我自己 自己的 ReactJS      更新时间:2023-09-26

是否有可能(甚至是一个好主意)将我自己的道具添加到另一个React组件中,比如:

<SomeCustomComponent myOwnParam={handler}>

正如Tyrsius所提到的,它实际上取决于SomeCustomComponent的实现。如果组件在任何地方都不使用myOwnParam道具,那么传递它将无法完成任何任务。另一方面,一些React组件可能会使用JSX扩展属性来引用代码中没有直接枚举的道具。

例如,以下SomeCustomComponent的实现将把您的myOwnParam道具传递给它的子div:

class SomeCustomComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    var {customComponentProp, ...other } = this.props;
    return (
      <div customComponentProp={customComponentProp} {...other}></div>
    );
  }
}

因此,这再次取决于SomeCustomComponent的实现会发生什么。

有关更多详细信息,请参阅传输道具文档:https://facebook.github.io/react/docs/transferring-props.html

这不会导致错误,但除非SomeCustomComponent正在寻找这个道具,否则不会对它做任何事情。组件在其道具上循环是可能的,所以这个可能是一个可用的策略,但我不确定你会对它做什么。你不能定义任何东西,只能对你事先不知道的属性定义迭代逻辑。