简体   繁体   English

这在 React 中意味着什么?

[英]What does this mean in React?

I was looking at some documentation for a React component and came across this syntax on line 2:我正在查看 React 组件的一些文档,并在第 2 行遇到了这种语法:

<NProgress isAnimating>
    {({ animationDuration, isFinished, progress }) => ( // <---- THIS LINE
      <Container animationDuration={animationDuration} isFinished={isFinished}>
        <Bar animationDuration={animationDuration} progress={progress} />
        <Spinner />
      </Container>
    )}
</NProgress>

What is this syntax and where did these variables come from?这是什么语法,这些变量是从哪里来的? I thought React components could only return JSX elements.我认为 React 组件只能返回 JSX 元素。 Could someone provide me with a simple example of how something like this is coded?有人可以给我一个简单的例子来说明这样的事情是如何编码的吗?

There are a couple of things happening, here.这里发生了几件事。

The () => {} notation is called an arrow function . () => {}符号称为箭头 function It's an ES6 way of declaring a function, with arguments in the parentheses and a function inside the curly braces.这是一种声明 function 的 ES6 方式,括号中为 arguments,花括号中为 function。

The {x, y, z} notation inside the parentheses is called a destructuring assignment.括号内的{x, y, z}符号称为解构赋值。 It takes an object and extracts the values of properties with the names x, y, and z into variables (in this case, as the inputs to an arrow function).它采用 object 并将名称为 x、y 和 z 的属性的值提取到变量中(在这种情况下,作为箭头函数的输入)。 That's where the variables are coming from inside the function.这就是变量来自 function 内部的地方。

This is one kind of pattern commonly used in React.js, ie render props as Patric said.这是React.js中常用的一种模式,即Patric所说的render props。 But it is using children props instead of "render" props.但它使用儿童道具而不是“渲染”道具。

Please have a look at this part of your code.请查看您的代码的这一部分。

  ({ animationDuration, isFinished, progress }) => (
    <Container animationDuration={animationDuration} isFinished={isFinished}>
      <Bar animationDuration={animationDuration} progress={progress} />
      <Spinner />
    </Container>
  )

This is a typical definition of functional component.这是功能组件的典型定义。 So, yes, children props of the NProgress component is a component.所以,是的,NProgress 组件的 children props 是一个组件。 The definition of NProgress component would looks like the following code. NProgress 组件的定义类似于以下代码。

export const NProgress = ({ children: Child }) => {
    return (
        <div className='container'>
            <h1>Progress</h1>
            <div className='content'>
                <Child animationDuration={10} isFinished={false} progress={3} />
            </div>
        </div>
    )
}

In the above code, typically the values(10, false, 3) would be typically state of the NProgress component.在上面的代码中,values(10, false, 3) 通常是 NProgress 组件的 state。

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

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