简体   繁体   English

分解纯功能组件中的道具

[英]Destructuring props in pure function components

Suppose we have the following pure function: 假设我们具有以下纯函数:

const HeaderComponent = () => (
  <h1> Title <h1>
)

export default HeaderComponent

Now I need to receive the new title from props, so we often destructure this.props to avoid accessing title with this.props.title and in the render method we will have something like: 现在,我需要从props接收新标题,因此我们经常对this.props进行this.props以避免使用this.props.title访问title ,并且在render方法中,我们将得到以下内容:

render() {
  const {Title} = this.props;
  return(
    <h1> {Title} </h1>
  )
}

The thing is we have to extend React.Component class to access render method. 关键是我们必须扩展React.Component类以访问渲染方法。

Is it possible to use the destructure in pure functions? 是否可以在纯函数中使用分解?

const HeaderComponent = props => (
   // const {Title} = this.props;
) 

You can do it like this. 您可以这样做。 I also find it a nice way of making the function self documenting. 我还发现它是使函数进行自我记录的好方法。

const HeaderComponent = ({ title }) => (
   <h1>{ title }<h1>
)

Also can set default values 也可以设置默认值

const HeaderComponent = ({ title: 'Default Title' }) => (
   <h1>{ title }<h1>
)

UPDATE: As TJ Crowder points out, Title is capitalized in your examples above. 更新:正如TJ Crowder指出的那样,在上面的示例中, Title大写。 In the text portion it is lowercase; 在文本部分为小写; as that is the norm, I have used the lowercase version 因为这是规范,所以我使用了小写版本

For your specific situation, see ken4z's answer , as parameter destructuring is the most concise way to do that. 对于您的特定情况,请参阅ken4z的答案 ,因为参数解构是最简洁的方法。

But in the general case: If you have logic you need to put in the arrow function prior to the return, just use the verbose form of arrow function: 但在一般情况下:如果您有逻辑,需要在返回之前放入arrow函数,只需使用arrow函数的详细形式即可:

const HeaderComponent = props => {
  const {Title} = props;
  // ....more logic can go here...
  return <h1>{Title}<h1>;
};

But again, you don't need that just to grab Title from props . 但是同样,您并不需要仅仅props获取Title


(Side note: It's unusual to capitalize the T in title when it's a property name or variable name...) (旁注:当它是属性名或变量名时,在title大写T是不寻常的。)

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

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