你如何为 React 中的嵌套形状提供默认props?

IT技术 javascript reactjs
2021-04-30 20:08:19

React 中有没有办法为特定形状的嵌套项目数组提供默认props?

鉴于下面的示例,可以看到我的第一次尝试,但这并没有按预期工作。

static propTypes = {
    heading: PT.string,
    items: PT.arrayOf(PT.shape({
        href: PT.string,
        label: PT.string,
    })).isRequired,
};

static defaultProps = {
    heading: 'this works',
    items: [{
        href: '/',
        label: ' - this does not - ',
    }],
};

在这个例子中,我期望以下内容:

// Given these props
const passedInProps = {
    items: [{ href: 'foo' }, { href: 'bar' }]
};

// Would resolve to:
const props = {
    heading: 'this works',
    items: [
      { href: 'foo', label: ' - this does not - ' },
      { href: 'bar', label: ' - this does not - ' },
    ]
};
2个回答

不。默认props只是浅合并。

但是,一种方法可能是为每个项目设置一个 Child 组件。这样每个子组件从item数组中接收一个对象,然后默认的 props 将按照你的预期进行合并。

例如:

var Parent = React.createClass({

  propTypes: {
    heading: React.PropTypes.string,
    items: React.PropTypes.arrayOf(React.PropTypes.shape({
      href: React.PropTypes.string,
      label: React.PropTypes.string,
    })).isRequired
  },

  getDefaultProps: function() {
    return {
      heading: 'this works',
      items: [{
        href: '/',
        label: ' - this does not - ',
      }],
    };
  },

  render: function() {
    return (
      <div>
        {this.props.item.map(function(item) {
          return <Child {...item} />
        })}
      </div>
    );
  }

});

var Child = React.createClass({

  propTypes: {
    href: React.PropTypes.string,
    label: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      href: '/',
      label: ' - this does not - '
    };
  },

  render: function() {
    return (
      <div />
        <p>href: {this.props.href}</p>
        <p>label: {this.props.label}
      </div>
    );
  }

});

您可以使用 getter 而不是调用this.props. 你必须有很多物品才能成为一种昂贵的方法。您也可以items像我在下面所做的那样进行修改,然后将其设置在 state 中,但 React 建议不要从 props 派生 state

class Foo extends React.Component {
  static propTypes = {
    heading: PropTypes.string,
    items: PropTypes.arrayOf(PropTypes.shape({
      href: PropTypes.string,
      label: PropTypes.string,
    })).isRequired
  }

  static defaultLabel = ' - this does not - '
  static defaultHref = '/'

  get items() {
    return this.props.items.map((item) => ({
      href: item.href || this.defaultHref,
      label: item.label || this.defaultLabel,
    }));
  }

  render() {
    return (
      <div>
        {this.items.map(({href, label}) => <a href={href}>{label}</a>)}
      </div>
    );
  }
}