【问题标题】:React - Pass function to component that has default propsReact - 将函数传递给具有默认道具的组件
【发布时间】:2018-12-17 15:50:48
【问题描述】:

我有一个使用默认道具的 React 组件:

class MyComponent extends Component {
  constructor(props) {
    console.log('props', props);
    super(props);

// rest of code here

}

MyComponent .defaultProps = {
  __TYPE: 'MyDateRange',
};

当我使用组件时,不传递任何道具,props 的控制台日志显示默认道具,就像它应该的那样。

现在,当我想传递一个额外的道具(在这种情况下是一个函数)时,像这样:

<MyComponent onEnterKey={() => console.log('snuh')}/>

props的控制台日志只显示onEnterKey函数。

我需要做什么才能让MyComponent 使用默认道具和接受一个函数?我尝试在MyComponent 的构造函数中添加另一个参数,但这不起作用。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您可以将defaultProp 放在构造函数之外的类上,如下所示:

class MyComponent extends Component {
  constructor(props) {
    console.log("props", props);
    super(props);
  }
  render() {
    return <div> test </div>;
  }
}

MyComponent.defaultProps = {
  __TYPE: "MyDateRange"
};

或者,您可以让defaultProps 成为类的静态属性:

class MyComponent extends Component {
  static defaultProps = {
    __TYPE: "MyDateRange"
  };
  constructor(props) {
    console.log("props", props);
    super(props);
  }
  render() {
    return <div> test </div>;
  }
}

【讨论】:

  • 您的第一个示例是当前的编码方式。对于第二个示例,我在等号处遇到语法错误:static defaultProps = ...
  • @BobHorn 类属性是一个stage-2 提议,因此您的开发环境可能没有它。您问题中的代码给人的印象是您在MyComponent 构造函数中 设置了MyComponent.defaultProps。不是这样吗?
  • 很抱歉,不是。默认设置在组件之后。我会更新问题。
  • 好的,这是我的一个错误。我以为我们的代码直接使用了组件。它不是。它引用一个索引文件,然后传递我们需要的道具。我会删除这个问题。对此感到抱歉。
  • @BobHorn 没关系。很高兴您发现了问题。
【解决方案2】:

我试过了,效果很好:

import React from "react";
import { render } from "react-dom";

class MyComponent extends React.Component {
  constructor(props) {
    console.log("props", props);
    super(props);
  }

  render() {
    return null;
  }
}

MyComponent.defaultProps = {
  __TYPE: "MyDateRange"
};

render(
  <MyComponent onEnterKey={() => console.log("snuh")} />,
  document.getElementById("app")
);

你可以在这里看到它:https://codesandbox.io/s/wkw0k0j5o8

【讨论】:

  • 那和我做的有什么不同?
  • __TYPE 显示,但实际属性(如 onChange 或范围)不显示。
  • 我不知道有什么不同(可能是括号位置),但是 onEnterKey 和 __TYPE 两个属性都显示在示例中。你检查过链接吗?
猜你喜欢
  • 2020-01-25
  • 2012-03-23
  • 2018-08-01
  • 2022-01-24
  • 2020-12-21
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多