Jak warunkowo dodać atrybuty do komponentów Reactowych?

Czy istnieje sposób na dodanie atrybutów do komponentu Reactowego tylko wtedy, gdy spełniony jest określony warunek?

Powinienem dodać wymagane i readOnly atrybuty do tworzenia elementów na podstawie wywołania ajax po renderowaniu, ale nie widzę, jak to rozwiązać, ponieważ readOnly= "false" nie jest tym samym, co całkowite pominięcie atrybutu.

Poniższy przykład powinien wyjaśnić, czego chcę, ale nie zadziała (błąd Parse: 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" : ""} />
        );
    }
});
Author: Remi Sture, 2015-07-01

11 answers

Najwyraźniej w przypadku pewnych atrybutów React jest wystarczająco inteligentny, aby pominąć atrybut, jeśli przekazywana wartość nie jest prawdziwa. Na przykład:

var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }
});

Spowoduje:

<input type="text" required data-reactid=".0.0">
 285
Author: juandemarco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-15 14:22:27

Po prostu rzucam inną opcję, ale @ juandemarco ' S odpowiedź jest zwykle poprawna.

Zbuduj obiekt jak chcesz:

var inputProps = {
  value: 'foo',
  onChange: this.handleChange
};

if (condition) inputProps.disabled = true;

Renderuj z spreadem, opcjonalnie przekazując również inne właściwości.

<input 
    value="this is overridden by inputProps" 
    {...inputProps} 
    onChange={overridesInputProps}
 />
 241
Author: FakeRainBrigand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-16 20:41:59

Oto przykład użycia Bootstrap's Button via React-Bootstrap.

var condition = true;

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

W zależności od warunku zostaną zwrócone {bsStyle: 'success'} lub {}. Operator spread rozprzestrzeni następnie Właściwości zwracanego obiektu na komponent Button. W przypadku falsy, ponieważ na zwracanym obiekcie nie istnieją żadne właściwości, nic nie zostanie przekazane do komponentu.


Alternatywny sposób oparty na komentarzu @ Andy Polhill poniżej:

var condition = true;

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

Jedyną małą różnicą jest to, że w drugim przykładzie wewnętrzny komponent <Button/> S props obiekt będzie miał klucz bsStyle o wartości undefined.

 146
Author: Arman Yeghiazaryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-30 15:44:15

Spóźnienie na imprezę. Oto alternatywa.

var condition = true;

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

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

Lub jego wersja inline

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);
 45
Author: Season,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-09 09:39:26

Możesz użyć tego samego skrótu, który służy do dodawania/usuwania (części) komponentów ({isVisible && <SomeComponent />}).

class MyComponent extends React.Component {
  render() {
    return (
      <div someAttribute={someCondition && someValue} />
    );
  }
}
 12
Author: GijsjanB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 14:49:12

Spóźnienie na imprezę.

Powiedzmy, że chcemy dodać właściwość niestandardową (używając aria - * lub data -*), jeśli warunek jest prawdziwy:

{...this.props.isTrue && {'aria-name' : 'something here'}}

Powiedzmy, że chcemy dodać właściwość stylu, jeśli warunek jest true:

{...this.props.isTrue && {style : {color: 'red'}}}
 6
Author: Mina Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-02 06:02:44

Jeśli używasz es6, możesz po prostu napisać w ten sposób.

// first, create a wrap object.
const wrap = {
    [variableName]: true
}
// then, use it
<SomeComponent {...{wrap}} />
 6
Author: snyh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-22 05:04:30

To powinno zadziałać, ponieważ twój stan zmieni się po wywołaniu ajax, a komponent macierzysty ponownie wyrenderuje.

render : function () {
    var item;
    if (this.state.isRequired) {
        item = <MyOwnInput attribute={'whatever'} />
    } else {
        item = <MyOwnInput />
    }
    return (
        <div>
            {item}
        </div>    
    );
}
 3
Author: Michael Parker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-01 14:18:23

Tak to zrobię.

Z Warunkowym :

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

Nadal wolę używać regularnego sposobu przekazywania rekwizytów w dół, ponieważ jest bardziej czytelny (moim zdaniem) w przypadku nie mają żadnych warunków.

Bez warunku :

 <Label text={label} type={type} tooltip={tooltip} isRequired={required} />
 2
Author: Tony Tai Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-15 21:11:39

Rozważając ten post https://facebook.github.io/react/tips/if-else-in-JSX.html możesz rozwiązać swój problem w ten sposób

if (isRequired) {
  return (
    <MyOwnInput name="test" required='required' />
  );
}
return (
    <MyOwnInput name="test" />
);
 0
Author: Viktor Kireev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-01 14:24:50

W Reaccie możesz warunkowo renderować komponenty, ale także ich atrybuty, takie jak props, className, id i inne.

W Reaccie bardzo dobrą praktyką jest używanie "operatora trójdzielnego", który może Ci pomóc warunkowo Renderuj Komponenty.

Przykład pokazuje również jak warunkowo renderować komponent i jego styl atribute

Oto prosty przykład:

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>
 0
Author: Juraj Sarissky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-18 18:45:02