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

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

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

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

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

当前回答

我有个办法。

带有条件句:

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

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

不带条件句:

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

其他回答

<input checked={true} type="checkbox"  />

对于React[1]列出的一些布尔属性:

<input disabled={disabled} />

// renders either `<input>` or `<input disabled>` 

其他属性:

<div aria-selected= {selected ? "" : undefined} />

// renders either `<div aria-selected></div>` or `<div></div>`

[1]布尔属性列表:https://github.com/facebook/react/blob/3f9480f0f5ceb5a32a3751066f0b8e9eae5f1b10/packages/react-dom/src/shared/DOMProperty.js#L318-L345

<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

我认为这可能对那些希望attribute的值是一个函数的人有用:

import { RNCamera } from 'react-native-camera';
[...]

export default class MyView extends React.Component {

    _myFunction = (myObject) => {
        console.log(myObject.type); //
    }

    render() {

        var scannerProps = Platform.OS === 'ios' ? 
        {
            onBarCodeRead : this._myFunction
        } 
        : 
        { 
            // here you can add attribute(s) for other platforms
        }

        return (
            // it is just a part of code for MyView's layout
            <RNCamera 
                ref={ref => { this.camera = ref; }}
                style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', }}
                type={RNCamera.Constants.Type.back}
                flashMode={RNCamera.Constants.FlashMode.on}
                {...scannerProps}
            />
        );
    }
}

这里有一个替代方案。

var condition = true;

var props = {
  value: 'foo',
  ...(condition && { disabled: true })
};

var component = <div {...props} />;

或者内联版本

var condition = true;

var component = (
  <div value="foo" {...(condition && { disabled: true })} /> 
);