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

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

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

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

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

当前回答

我认为这可能对那些希望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}
            />
        );
    }
}

其他回答

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


    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} />
    }

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

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}
                    />
    );
}

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

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

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

  return (
    <Container {...otherProps} >

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

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

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