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

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

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

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

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

当前回答

在React中,你可以有条件地呈现组件,还有它们的属性,比如props、className、id等等。

在React中,使用三元运算符是一个很好的实践,它可以帮助你有条件地呈现组件。

一个示例还展示了如何有条件地呈现Component及其样式属性。

这里有一个简单的例子:

class App extends React.Component { state = { isTrue: true }; render() { return ( <div> {this.state.isTrue ? ( <button style={{ color: this.state.isTrue ? "red" : "blue" }}> I am rendered if TRUE </button> ) : ( <button>I am rendered if FALSE</button> )} </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

其他回答

以一种简单的方式

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

像这样使用它

<InputText required disabled/>

这里有一个替代方案。

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 })} /> 
);
<Button {...(isWeb3Enabled ? {} : { isExternal: true })}>
    Metamask
</Button>

下面是一个通过React-Bootstrap(0.32.4版本)使用Bootstrap按钮的例子:

var condition = true;

return (
  <Button {...(condition ? {bsStyle: 'success'} : {})} />
);

根据条件,将返回{bsStyle: 'success'}或{}。然后,扩展操作符将返回对象的属性扩展到Button组件。在falsy情况下,由于返回的对象上不存在任何属性,因此不会向组件传递任何内容。


另一种基于Andy Polhill评论的方法是:

var condition = true;

return (
  <Button bsStyle={condition ? 'success' : undefined} />
);

唯一的小区别是,在第二个例子中,内部组件<Button/>的props对象将有一个值为undefined的键bsStyle。

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