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

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

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

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

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

当前回答

如果您使用ECMAScript 6,您可以像这样简单地编写。

// First, create a wrap object.
const wrap = {
    [variableName]: true
}
// Then, use it
<SomeComponent {...{wrap}} />

其他回答

这里有一个替代方案。

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

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

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

const name = "someName";

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

在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>

这应该是可行的,因为在Ajax调用之后,您的状态将会改变,并且父组件将重新呈现。

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>
    );
}