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

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

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

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

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

当前回答

此外,还可以将其他值设置为布尔值

const MyComponent = function() {
    const Required = "yes";

    return (
         <input
                      required={Required === "yes"}
                      type="text"
                      key={qs.Name}
                      name="DefaultValue"
                      label={qs.QuestionTitle}
                      onChange={(event) => handleInputChange(index, event)}
                      placeholder={qs.QuestionTitle}
                    />
    );
}

其他回答

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

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

你可以在你的渲染方法(如果使用类)或返回语句(如果使用函数组件)中执行以下操作:

 <MyComponent required={isRequired ? 'true' : undefined} />

在这种情况下,如果isRequired为undefined、false或null(这与添加属性但将其设置为'false'不同),则属性将不会被添加。还要注意,我使用字符串而不是布尔值,以避免来自react的警告消息(在非布尔属性上接收布尔值)。

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

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

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

我有个办法。

带有条件句:

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

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

不带条件句:

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