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

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

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

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

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

当前回答

胡德马科的答案通常是正确的,但这里有另一种选择。

创建一个你喜欢的对象:

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition) {
  inputProps.disabled = true;
}

渲染与蔓延,可选的传递其他道具也。

<input
    value="this is overridden by inputProps"
    {...inputProps}
    onChange={overridesInputProps}
 />

其他回答

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

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

在react函数组件中,你可以尝试这样做来省略不必要的标签属性。

<div className="something" ref={someCondition ? dummyRef : null} />

这适用于我,如果我需要省略标签,如ref, class等。但我不知道这是否适用于每个标签属性

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

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

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

{...this.props.isTrue && {style : {color: 'red'}}}
<input checked={true} type="checkbox"  />

例如,为自定义容器使用属性样式

const DriverSelector = props => {
  const Container = props.container;
  const otherProps = {
    ...( props.containerStyles && { style: props.containerStyles } )
  };

  return (
    <Container {...otherProps} >