是否有一种方法只在满足特定条件时才向React组件添加属性?

我应该添加必需的和readOnly属性,以形成基于Ajax调用后呈现的元素,但我不知道如何解决这个问题,因为readOnly="false"并不等同于完全省略属性。

下面的例子应该解释我想要什么,但它不起作用。

(解析错误:意外的标识符)

function MyInput({isRequired}) {
  return <input classname="foo" {isRequired ? "required" : ""} />
}

当前回答

我有个办法。

带有条件句:

<Label
    {...{
      text: label,
      type,
      ...(tooltip && { tooltip }),
      isRequired: required
    }}
/>

我仍然喜欢使用常规的传递道具的方式,因为在没有任何条件的情况下,它更具可读性(在我看来)。

不带条件句:

<Label text={label} type={type} tooltip={tooltip} isRequired={required} />

其他回答

下面是一个通过React-Bootstrap(0.32.4版本)使用Bootstrap按钮的例子:

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

根据条件,将返回{bsStyle: 'success'}或{}。然后,扩展操作符将返回对象的属性扩展到Button组件。在falsy情况下,由于返回的对象上不存在任何属性,因此不会向组件传递任何内容。


另一种基于Andy Polhill评论的方法是:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

唯一的小区别是,在第二个例子中,内部组件<Button/>的props对象将有一个值为undefined的键bsStyle。

考虑到JSX深度文章,你可以这样解决你的问题:

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);

在react函数组件中,你可以尝试这样做来省略不必要的标签属性。

<div className="something" ref={someCondition ? dummyRef : null} />

这适用于我,如果我需要省略标签,如ref, class等。但我不知道这是否适用于每个标签属性

我有个办法。

带有条件句:

<Label
    {...{
      text: label,
      type,
      ...(tooltip && { tooltip }),
      isRequired: required
    }}
/>

我仍然喜欢使用常规的传递道具的方式,因为在没有任何条件的情况下,它更具可读性(在我看来)。

不带条件句:

<Label text={label} type={type} tooltip={tooltip} isRequired={required} />

当您不需要该属性时,必须将其值设置为未定义 例子:

<a data-tooltip={sidebarCollapsed?'Show details':undefined}></a>