我在 React.js 功能组件中注意到,如:
import React from 'react';
import ReactDOM from 'react-dom';
function MyComponent(props, whatIsThisFor) {
console.log(JSON.stringify(whatIsThisFor)); // logs {} to console
return <div></div>
}
ReactDOM.render(<MyComponent />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
在whatIsThisFor呈现时参数会设置为空对象。我在任何文档中都找不到此参数的用途。有谁知道它是做什么用的?
正如您所调查的,第二个参数是使用React.forwardRef(…)API转发的。在 docs - Forwarding refs to DOM components - 您可以找到有关该主题的更多信息。
编辑:
链接代码中的第二个参数称为refOrContext。这意味着,参数也可能是 acontext并且它似乎是Legacy Context API的一部分。
注意:不要使用 Legacy Context API;改用新的Context API。
简而言之,当您contextTypes在功能组件中定义字段时,您将收到一个具有定义形状的对象作为第二个参数。如果该组件嵌套在另一个实现getChildContext并返回带有某些字段的对象的类组件下,则这些字段context仅在您将它们标记为contextTypes. 这是组件的示例:
import PropTypes from 'prop-types';
const ContextConsumer = (props, context) => {
console.log(context); // { name: … }
return …;
};
ContextConsumer.contextTypes = {
name: PropTypes.string,
…
};
export default ContextConsumer;
Run Code Online (Sandbox Code Playgroud)
完整的示例可以在我的 StackBlitz 上找到。有关更多信息,请阅读 Legacy context API。
| 归档时间: |
|
| 查看次数: |
2403 次 |
| 最近记录: |