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

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

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

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

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

当前回答

使用undefined适用于大多数属性:

const name = "someName";

return (
    <input name={name ? name : undefined} />
);

其他回答

这应该是可行的,因为在Ajax调用之后,您的状态将会改变,并且父组件将重新呈现。

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>
    );
}

显然,对于某些属性,React足够智能,如果传递给它的值不是真值,它会省略该属性。例如:

const InputComponent = function() {
    const required = true;
    const disabled = false;

    return (
        <input type="text" disabled={disabled} required={required} />
    );
}

会导致:

<input type="text" required>

更新:如果有人好奇这种情况是如何发生的,你可以在ReactDOM的源代码中找到详细信息,特别是在DOMProperty.js文件的第30行和167行。

如果您使用ECMAScript 6,您可以像这样简单地编写。

// First, create a wrap object.
const wrap = {
    [variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />

使用undefined适用于大多数属性:

const name = "someName";

return (
    <input name={name ? name : undefined} />
);
<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>