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

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

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

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

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

当前回答

<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

其他回答

假设我们想要在条件为真时添加一个自定义属性(使用aria-*或data-*):

{...this.props.isTrue && {'aria-name' : 'something here'}}

假设我们想在条件为真时添加一个style属性:

{...this.props.isTrue && {style : {color: 'red'}}}

这里有一个替代方案。

var condition = true;

var props = {
  value: 'foo',
  ...(condition && { disabled: true })
};

var component = <div {...props} />;

或者内联版本

var condition = true;

var component = (
  <div value="foo" {...(condition && { disabled: true })} /> 
);

以一种简单的方式

const InputText= ({required = false , disabled = false, ...props}) => 
         (<input type="text" disabled={disabled} required={required} {...props} />);

像这样使用它

<InputText required disabled/>

下面是一个通过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。

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

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