是否有一种方法只在满足特定条件时才向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}
 />

其他回答

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

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

  return (
    <Container {...otherProps} >

我认为这可能对那些希望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}
            />
        );
    }
}
<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

使用undefined适用于大多数属性:

const name = "someName";

return (
    <input name={name ? name : undefined} />
);

以一种简单的方式

const InputText= ({required = false , disabled = false, ...props}) => 
         (<input type="text" disabled={disabled} required={required} {...props} />);

像这样使用它

<InputText required disabled/>