简体   繁体   English

这是在反应中使用功能组件中的道具的正确方法

[英]which is the correct way while using props in functional component in react

which one is the correct way in react functional component and why? 哪一个是反应功能组件的正确方法,为什么?

Way 1: 方式1:

export function renderElements(props) {

   let { value, element } = props;
   return (
     <!--- Code----!>
   )
}

renderElements.defaultProps = {
   value: 0,
   element: 'Hello'
}

Way 2 方式2

export function renderElements({
   value = 0,
   element = 'Hello'
}) {
   return (
     <!--- Code----!>
   )
}

Can you please suggest? 你能建议吗?

There's no correct way, both ways can acceptable, depending on a case. 没有正确的方法,两种方式都可以接受,具体取决于案例。 The difference is that objects ( <b>hi</b> is React element, which is an object) will be same with defaultProps . 区别在于对象( <b>hi</b>是React元素,它是一个对象)与defaultProps相同。 This may result in undesirable behaviour if prop values are mutated by a component: 如果prop值被组件变异,这可能会导致不良行为:

export function renderElements(props) {
   let { value, element } = props;
   element.props.children = value; // affects all renderElements instances at once

   return element;
}

renderElements.defaultProps = {
   value: 0,
   element: <b>hi</b>
}

This may be not a problem if objects are immutable ( React.cloneElement in case of React element), which is preferable way to do things in React. 如果对象是不可变的(在React元素的情况下是React.cloneElement ),这可能不是问题,这是在React中做事的最好方法。

Both ways are correct. 两种方式都是正确的。 But for me, the second way is better because I am using it also code looks cool. 但对我来说,第二种方式更好,因为我使用它也代码看起来很酷。 You can initialize values in that case just to avoid code breaking and you are not receiving expected values 在这种情况下,您可以初始化值,以避免代码中断,并且您没有收到预期的值

instead of using the function key wort, it's better to use es6 syntax for functional components. 而不是使用功能键麦芽汁,最好使用es6语法的功能组件。

`export const renderElements = ({
   value = 0,
   element = <b>hi</b>
 }) => {
   return (
     <!--- Code----!>
   )
 }`

or if you want to return only a single element or object you can use shorter syntax like: 或者如果您只想返回单个元素或对象,可以使用更短的语法,如:

`export const renderElements = ({
   value = 0,
   element = <b>hi</b>
}) => <!--- Code----!>`

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

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