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

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

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

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

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

当前回答

在react函数组件中,你可以尝试这样做来省略不必要的标签属性。

<div className="something" ref={someCondition ? dummyRef : null} />

这适用于我,如果我需要省略标签,如ref, class等。但我不知道这是否适用于每个标签属性

其他回答

您可以使用相同的快捷方式,用于添加/删除组件({isVisible && <SomeComponent />})的(部分)。

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}

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

我有个办法。

带有条件句:

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

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

不带条件句:

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

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

const name = "someName";

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

对于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