How do I conditionally add attributes to React com

2020-01-25 03:28发布

Is there a way to only add attributes to a React component if a certain condition is met?

I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

The example below should explain what I want, but it won't work (Parse Error: Unexpected identifier).

var React = require('React');

var MyOwnInput = React.createClass({
    render: function () {
        return (
            <div>
                <input type="text" onChange={this.changeValue} value={this.getValue()} name={this.props.name}/>
            </div>
        );
    }
});

module.exports = React.createClass({
    getInitialState: function () {
        return {
            isRequired: false
        }
    },
    componentDidMount: function () {
        this.setState({
            isRequired: true
        });
    },
    render: function () {
        var isRequired = this.state.isRequired;

        return (
            <MyOwnInput name="test" {isRequired ? "required" : ""} />
        );
    }
});

11条回答
Explosion°爆炸
2楼-- · 2020-01-25 03:34

If you use es6, you can simply write like this.

// first, create a wrap object.
const wrap = {
    [variableName]: true
}
// then, use it
<SomeComponent {...{wrap}} />
查看更多
Deceive 欺骗
3楼-- · 2020-01-25 03:39

Considering this post JSX In Depth you can solve your problem this way

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);
查看更多
姐就是有狂的资本
4楼-- · 2020-01-25 03:40

Late to the party. Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...( condition && { disabled: true } )
};

var component = <div { ...props } />;

Or its inline version

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);
查看更多
狗以群分
5楼-- · 2020-01-25 03:40

You can use the same shortcut, which is used to add/remove (parts of) components ({isVisible && <SomeComponent />}).

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}
查看更多
▲ chillily
6楼-- · 2020-01-25 03:40

In React you can conditionally render Components but also their attributes like props, className, id, and more.

In React it's very good practice to use "Ternary operator" which can help you conditionally render Components.

Example shows also how to conditionally render Component and its style atribute

Here is simple example :

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>

查看更多
Explosion°爆炸
7楼-- · 2020-01-25 03:41

This should work, since your state will change after the ajax call, and the parent component will re-render.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>    
    );
}
查看更多
登录 后发表回答