Подтвердить что ты не робот

Как вы предоставляете реквизиты по умолчанию для вложенной формы в React?

Есть ли способ в React предоставить реквизиты по умолчанию для вложенного массива элементов определенной формы?

Учитывая приведенный ниже пример, можно увидеть мою первую попытку, однако это не работает, как ожидалось.

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 - ' },
    ]
};
4b9b3361

Ответ 1

Нет. Репозитории по умолчанию только мелко сливаются.

Однако одним из подходов может быть наличие дочернего компонента для каждого элемента. Таким образом, каждый дочерний компонент получает один объект из массива item, а затем реквизиты по умолчанию будут объединены, как вы ожидаете.

Например:

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>
    );
  }

});

Ответ 2

Вы можете использовать геттер вместо вызова this.props. У вас должно быть много вещей, чтобы это был дорогой метод. Вы также можете изменить items, как я это сделал ниже, и затем установить его в состояние, но React рекомендует не создавать состояние из реквизита.

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>
    );
  }
}