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

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

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

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

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

当前回答

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

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

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

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

其他回答

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

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

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

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

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

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

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


    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} />
    }
<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

我有个办法。

带有条件句:

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

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

不带条件句:

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