Skip to main content
 首页 » 编程设计

javascript之ReactJS:将我自己的 Prop 添加到另一个组件

2025年01月19日8Renyi-Fan

是否可以(甚至是一个好主意)将我自己的 Prop 添加到另一个 React 组件中,例如:

<SomeCustomComponent myOwnParam={handler}> 

请您参考如下方法:

正如 Tyrsius 所提到的,它实际上取决于 SomeCustomComponent 的实现。如果组件没有在任何地方使用 myOwnParam 属性,传递它不会完成任何事情。另一方面,一些 React 组件可能会使用 JSX 传播属性来引用代码中未直接枚举的 props。

例如,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 的实现会发生什么。

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