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

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

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

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

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

当前回答

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

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

其他回答

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

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

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

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

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

如果是有限数量的属性,这将做


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

如果您有大量的属性,那么很难为每个属性编写If else条件并相应地返回。为此,您可以将这些属性推入到对象中,并在返回元素中使用展开操作符。

    function MyInput({ prop1, prop2, ...propN }) {
        const props = {};
        if (prop1) props.prop1 = prop1;
        .
        .
        .
        if (propN) props.propN = propN;
        return <input classname="foo" {...props} />
    }

显然,对于某些属性,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行。

在React中,我们将值作为Props从父组件传递给子组件。如果值为false,则不会将其作为道具传递。在某些情况下,我们也可以使用三元(条件运算符)。