0

我是 React 新手,正在尝试了解 React-Popper。这是一些代码

https://www.npmjs.com/package/react-popper

“ref”、“style”、“placement”和“arrowProps”的值来自哪里,我将如何编辑它们?我知道您可以使用 this.props 和属性将值传递给组件,但我不明白要插入函数的值来自哪里。

import { Manager, Reference, Popper } from 'react-popper';

const Example = () => (
  <Manager>
    <Reference>
      {({ ref }) => (
        <button type="button" ref={ref}>
          Reference element
        </button>
      )}
    </Reference>
    <Popper placement="right">
      {({ ref, style, placement, arrowProps }) => (
        <div ref={ref} style={style} data-placement={placement}>
          Popper element
          <div ref={arrowProps.ref} style={arrowProps.style} />
        </div>
      )}
    </Popper>
  </Manager>
);
4

2 回答 2

1

你在这里看到的是一个箭头函数,它与解构赋值React Render Props相结合。所以在一个代码示例中有很多内容。

从您的问题来看,我认为最让您困惑的是解构分配。所以这里有一个例子,希望对你有帮助:

var foo = ({a, b}) => a + b;

var x = {
  a: 1,
  b: 2
};

console.log(foo(x));
# Output is 3

这是因为解构赋值将对象中的值分配给变量ab就好像它们是函数参数一样。React 组件上的对象也发生了同样的事情props,这就是你看不到props.ref等的原因。

于 2019-05-06T19:49:27.140 回答
0

它们是Popper 组件的渲染道具。它们都是Popper文件中定义的 render prop 函数的参数,你可以在 GitHub 上找到这个包的。我不熟悉这个特定的库,但基本上它们被传递给该函数,并且它们需要按定义存在,否则会引发错误。您应该能够计算自己的样式值和诸如此类的值,但我再次不熟悉这个包。

于 2019-05-06T19:44:49.790 回答